Crossthread operation not valid... - VB.NET

The purpose of the BackgroundWorker class is to perform work on a non-GUI thread while the GUI remains responsive. Unless you set Control.CheckForIllegalCrossThreadCalls to false (which you shouldn't do), or use Invoke as suggested in the other answers (which I also wouldn't recommend), you're going to get an illegal cross-thread operation exception.

If you want GUI-related "stuff" to happen while your BackgroundWorker is running, I'd generally recommend using the BackgroundWorker.ReportProgress method and attaching an appropriate handler to the BackgroundWorker.ProgressChanged event. If you want something on the GUI to happen once the BackgroundWorker is finished, then simply attach your handler to update the GUI to the BackgroundWorker.RunWorkerCompleted event.


Type the following code in the Form1_Load (or whatever your form is) sub:

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False

It fixes all problems with blocked cross-thread operations.


Better way to this in VB.NET is to use a Extension it makes very nice looking code for cross-threading GUI Control Calls.

Just add this line of code to any Module you have.

<System.Runtime.CompilerServices.Extension()> _
Public Sub Invoke(ByVal control As Control, ByVal action As Action)
    If control.InvokeRequired Then
        control.Invoke(New MethodInvoker(Sub() action()), Nothing)
    Else
        action.Invoke()
    End If
End Sub

Now you can write Cross-Thread Control code that's only 1 line long for any control call.

Like this, lets say you want to clear a ComboBox and it's called from threads or without threads you can just use do this now

cboServerList.Invoke(Sub() cboServerList.Items.Clear())

Want to add something after you clear it?

cboServerList.Invoke(Sub() cboServerList.Items.Add("Hello World"))