不能從除線程的線程上改變大多數控件屬性哪個控件是創建的。
檢查是否需要調用,即當前的代碼在除其中控制(文本框試驗)已創建的線程以外的線程中執行。如果test.InvokeRequired
爲真,那麼您應該調用該調用。
Private Sub ...
Dim powershellWorker As New BackgroundWorker
AddHandler powershellWorker.DoWork, AddressOf BackgroundWorker1_DoWork
powershellWorker.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If stuff <> "lol" Then
If test.InvokeRequired Then
test.Invoke(Sub() test.Text = stuff)
Else
test.Text = stuff
End If
End If
End Sub
您可以自動使用這個擴展方法的調用所需的模式:
<Extension()>
Public Sub InvokeIfRequired(ByVal control As Control, action As MethodInvoker)
If control.InvokeRequired Then
control.Invoke(action)
Else
action()
End If
End Sub
那麼你的代碼可以簡化爲:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If stuff <> "lol" Then
test.InvokeIfRequired(Sub() test.Text = stuff)
End If
End Sub
來源
2016-07-06 19:09:51
djv
UI組件只能在線程上更新了創造它們。使用Textbox的'.Invoke()'方法從後臺線程執行此操作。 –
[VB.net設置值到背景工作者內部的標籤]可能的重複(http://stackoverflow.com/questions/18844490/vb-net-setting-values-to-labels-inside-a-backgroundworker) – topshot