backgroundworker cross thread

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
I have a backgroundworker at design and in ProgressChanged i added a flowlayoutpanel control and everything works fine.
But if i create the backgroundworker dynamically and on its progressChanged, add a flowlayoutpanel control, it will give me cross thread error. why is that?
 
Because you called the RunWorkerAsync method from a secondary thread, that is method is where the BackgroundWorker sets up its internal threading context, to where it raises the events.
 
I still don't understand it. How can you fix the dynamic one so it doesn't give cross thread error?
 
Whichever thread you call RunWorkerAsync on is the thread that the ProgressChanged and RunWorkerCompleted events will be raised on. If you need to update the UI in the handlers for those events then you need those events to be raised on the UI thread, which means that you have to call RunWorkerAsync on the UI thread. If you are experiencing cross-thread exceptions in either of those two event handlers then either you are not calling RunWorkerAsync on the UI thread or, less likely, you are trying to access controls that were not created on the UI thread.

If that still doesn't clear it up then do the obvious thing and show us your (relevant) code.
 
oh i think i was calling the dynamic backgroundworker from another backgroundworker's dowork. Thats why its cross thread.
 
That would do it. I have to say, especially in .NET 4.0, it's rarely a good idea to create BackgroundWorkers in code. If you can't create it at design time then you probably ought to be looking at a different multi-threading option. In .NET 4.0 you have the System.Threading.Tasks namespace, which is the preferred option.
 
Back
Top