Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crossthread operation not valid... - VB.NET

I am using vb.net, and in my program I get this 'crossthread operation not valid' error when I run my backgroundworker that will make this textbox enabled true. My main sub will first turn the enabled to false, and when the backgroundworker runs it will turn it back true then exit. Why does it give me an error? FYI: There is more code to this but I don't want to make it any more confusing...

Here is the stack trace:

at System.Windows.Forms.Control.get_Handle()
   at System.Windows.Forms.Control.OnEnabledChanged(EventArgs e)
   at System.Windows.Forms.Control.set_Enabled(Boolean value)
   at Helium.Form1.BackgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in C:\Users\Kevin\documents\visual studio 2010\Projects\Helium\Helium\Form1.vb:line 167
   at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
   at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

and here is the exact error message:

{"Cross-thread operation not valid: Control 'mainText' accessed from a thread other than the thread it was created on."}

Can someone please help me out!

Thanks,

KEvin

like image 779
lab12 Avatar asked Feb 10 '10 22:02

lab12


2 Answers

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.

like image 128
Dan Tao Avatar answered Sep 22 '22 08:09

Dan Tao


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.

like image 23
alex Avatar answered Sep 22 '22 08:09

alex