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
The purpose of the
BackgroundWorkerclass is to perform work on a non-GUI thread while the GUI remains responsive. Unless you setControl.CheckForIllegalCrossThreadCallstofalse(which you shouldn’t do), or useInvokeas 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
BackgroundWorkeris running, I’d generally recommend using theBackgroundWorker.ReportProgressmethod and attaching an appropriate handler to theBackgroundWorker.ProgressChangedevent. If you want something on the GUI to happen once theBackgroundWorkeris finished, then simply attach your handler to update the GUI to theBackgroundWorker.RunWorkerCompletedevent.