Cross-thread operation not valid
May 14th, 2008Sometimes you need to create a new thread in a windows form to do a parallel job, and (usually) want to update some windows controls based on what the worker thread is doing (typically incrementing a progress bar). There are two simple ways to access a control from a worker thread:
1) Passing the control to the thread:
The WorkerMethod being:
2)Providing an event which the worker method fires and the windows form handles - preferred:
Event Declaration (in the class containing the WorkerMethod):
Event firing (in WorkerMethod whenever needed):
Subscribing to the event (in the windows form):
Handling the event (in the windows form):
Main Point: Now when you try to access your windows control in the WorkerMethod or the event handler, you get the following exception:
Cross-thread operation not valid: Control ‘progressBar’ accessed from a thread other than the thread it was created on.
Without talking about the what and why, here is how to get to your control:
Mahdieh