hannir
hannir

Reputation: 95

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)

Upvotes: 1

Views: 2857

Answers (2)

ALUM22
ALUM22

Reputation: 111

This is brief and seems to work fine:

Label1.Invoke(Sub() Label1.Text = "MEOW")

Upvotes: 0

djv
djv

Reputation: 15774

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

Upvotes: 3

Related Questions