hannir hannir - 5 months ago 43
Vb.net Question

How to change textbox.text while in backgroundworker?

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)

Answer

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