2012-01-02 46 views
2

我正在使用BackgroundWorker來完成繁重的任務,所以UI線程不會被阻塞。雖然BackgroundWorker可以使用progress-scheme將值發送到UI線程,但BackgroundWorker如何從UI線程獲取一些值?BackgroundWorker在UI線程運行時如何獲取值?

要麼通過詢問它,要麼通過UI線程向BackgroundWorker發送一些值?

只是在BackgroundWorker內訪問像UIForm.x這樣的UI線程變量不起作用,它似乎沒有訪問UI變量的功能?

非常感謝

+0

RunWorkerAsync()可以將Object作爲參數。這可能是您創建的用於存儲工作人員需要的UI值的類的對象。 – 2012-01-02 13:16:33

+0

謝謝,但我不需要這些值只是爲了啓動工作人員 - 工作人員已經在UI線程中多次獲取值。我應該在我的問題中更清楚地說明... – user387184 2012-01-02 13:57:39

+0

然後你做錯了。當價值觀念發生變化時,這是完全不可預測的,保持工人在等待用戶再次醒來沒有意義。當這個值發生變化時,再次啓動員工。 – 2012-01-02 14:08:44

回答

4

除UI線程之外的其他線程都不允許訪問UI。你可能用worker.RunWorkerAsync()啓動了BackgroundWorker。您也可以用worker.RunWorkerAsync(someObject)開始。在工作人員正在運行時,您不能傳遞新對象,但可以更改對象本身的內容。由於對象類型是引用類型,因此UI線程和工作線程將看到相同的對象內容。

Imports System.ComponentModel 
Imports System.Threading 

Class BgWorkerCommunication 
    Private _worker As BackgroundWorker 

    Private Class WorkParameters 
     Public text As String 
    End Class 

    Public Sub DoRun() 
     Dim param = New WorkParameters() 

     _worker = New BackgroundWorker() 
     AddHandler _worker.DoWork, New DoWorkEventHandler(AddressOf _worker_DoWork) 
     AddHandler _worker.RunWorkerCompleted, New RunWorkerCompletedEventHandler(AddressOf _worker_RunWorkerCompleted) 

     param.text = "running " 
     _worker.RunWorkerAsync(param) 
     While _worker.IsBusy 
      Thread.Sleep(2100) 
      param.text += "." 
     End While 
    End Sub 

    Private Sub _worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) 
     Console.WriteLine("Completed") 
    End Sub 

    Private Sub _worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) 
     Dim param = DirectCast(e.Argument, WorkParameters) 
     For i As Integer = 0 To 9 
      Console.WriteLine(param.text) 
      Thread.Sleep(1000) 
     Next 
    End Sub 
End Class 
+0

完美!這像一個魅力。非常感謝! – user387184 2012-01-02 15:00:37

相關問題