除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
RunWorkerAsync()可以將Object作爲參數。這可能是您創建的用於存儲工作人員需要的UI值的類的對象。 – 2012-01-02 13:16:33
謝謝,但我不需要這些值只是爲了啓動工作人員 - 工作人員已經在UI線程中多次獲取值。我應該在我的問題中更清楚地說明... – user387184 2012-01-02 13:57:39
然後你做錯了。當價值觀念發生變化時,這是完全不可預測的,保持工人在等待用戶再次醒來沒有意義。當這個值發生變化時,再次啓動員工。 – 2012-01-02 14:08:44