How to change textbox.text while in backgroundworker?

喜欢而已 提交于 2019-12-11 12:36:14

问题


I just want to change an textbox text while I am in the backgroundworker. What I have is:

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

It gives me the error: "Invalid thread -border operation" (google translated)


回答1:


You can't change most control properties from a thread other than the thread in which the control was created.

Check if invoke is required, i.e. the current code is executing on a thread other than the thread in which the control (TextBox test) was created. If test.InvokeRequired is true, then you should Invoke the call.

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

You can automate the invoke required pattern with this extension method:

<Extension()>
Public Sub InvokeIfRequired(ByVal control As Control, action As MethodInvoker)
    If control.InvokeRequired Then
        control.Invoke(action)
    Else
        action()
    End If
End Sub

Then your code could be simplified to:

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


来源:https://stackoverflow.com/questions/38230640/how-to-change-textbox-text-while-in-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!