如何在backgroundworker中更改textbox.text?

时间:2016-07-06 17:56:11

标签: vb.net backgroundworker

我只想在后台工作时更改文本框文本。 我所拥有的是:

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

它给了我错误:&#34;无效的线程 - 边界操作&#34; (谷歌翻译)

1 个答案:

答案 0 :(得分:3)

您无法从创建控件的线程以外的线程更改大多数控件属性。

检查是否需要调用,即当前代码是在创建控件(TextBox测试)的线程以外的线程上执行的。如果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