C# Cross-thread Operations

When you start creating multi-threaded applications in .NET you’ll soon attempt to update a form control from a thread other than the main program thread. If you do, you’ll run into this:

InvalidOperationException: Cross-thread operation not valid: Control ‘xxx’ accessed from a thread other than the thread it was created on.

You can’t directly update a form control that was created on a different thread. Lets say we have a label (lblStatus) that is updated by the method UpdateStatus. We want to update the status to say “Done” when the background worker is complete.

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  // Some long running code
  // ...

  UpdateStatus("Done");
}

Our delegate and UpdateStatus method would look like this:

private delegate void UpdateStatusDelegate(string message);

private void UpdateStatus(string message)
{
  if (this.InvokeRequired)
    this.Invoke(new UpdateStatusDelegate(this.UpdateStatus), message);
  else
    lblStatus.Text = message;
}

Alternatively, we can use a MethodInvoker and drop the explicit delegate declaration:

private void UpdateStatus(string message)
{
  if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate() { this.UpdateStatus(message); }));
  else
    lblStatus.Text = message;
}

Personally I find the latter quicker and neater, but they both do the same thing.

Advertisements
This entry was posted in Reference and tagged , , . Bookmark the permalink.

2 Responses to C# Cross-thread Operations

  1. Thank you for the help.
    Will this work in Windows 7?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s