Cross-thread operation not valid

Sometimes 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:

Thread workerThread = new Thread(WorkerMethod);
workerThread.Start(myProgressBar);

The WorkerMethod being:

void WorkerMethod(object myProgressBar)
{...}

2)Providing an event which the worker method fires and the windows form handles - preferred:
Event Declaration (in the class containing the WorkerMethod):

event EventHandler UpdateUI;

Event firing (in WorkerMethod whenever needed):

if(UpdateUI != null)
UpdateUI(this, new EventArgs());

Subscribing to the event (in the windows form):

UpdateUI += new EventHandler(MyForm_UpdateUI);

Handling the event (in the windows form):

private void MyForm_UpdateUI(object sender, EventArgs e)
{ // update the control (progress bar) here }

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:

progressBar.Invoke(new MethodInvoker(
delegate { progressBar.Increment(); }));

Mahdieh

Tags: , ,

Leave a Reply