2016-07-06 44 views
1

我只是想在後臺工作時更改文本框文本。 我所擁有的是:如何在backgroundworker中更改textbox.text?

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 
      test.Text = stuff 

End Sub 

它給我的錯誤:「無效的線程-border操作」(谷歌翻譯)

+2

UI組件只能在線程上更新了創造它們。使用Textbox的'.Invoke()'方法從後臺線程執行此操作。 –

+2

[VB.net設置值到背景工作者內部的標籤]可能的重複(http://stackoverflow.com/questions/18844490/vb-net-setting-values-to-labels-inside-a-backgroundworker) – topshot

回答

2

不能從除線程的線程上改變大多數控件屬性哪個控件是創建的。

檢查是否需要調用,即當前的代碼在除其中控制(文本框試驗)已創建的線程以外的線程中執行。如果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 
+0

嘗試所有 - 它只是美麗的作品! thx很多老兄!那麼,還有一個問題:如何在後臺工作中啓動計時器? 「Timer2.Invoke(Sub()Timer2.Start())」可悲的是不工作。 – hannir

+0

找到了定時器啓動的解決方案:)「timerclick.Invoke(Sub()timerclick.PerformClick())」只需點擊一個按鈕啓動計時器。 – hannir

相關問題