Sunday, October 19, 2008

C# Cross-Thread Operations made easy

Starting with .Net Framework 2.0 and higher, it's a must to write cross-thread operations.

Cross-thread operations in C# are calls on the method that attempts to access an object that was created in a different thread.

Lets say we would like to load data into a DropDown Control from a Background thread we will receive the following error:

Cross-thread operation not valid: Control 'Abc' accessed from a thread other than the thread it was created on.

We can solve this by using simple delegate and the attribute InvokeRequired. Lets look on 2 samples how to succeed with this once with and once without a parameter:


   1:  private delegate void DelegateManageLink(string url, bool isEmail);

   2:   

   3:  private void ManageLink(string url, bool isEmail)

   4:  {

   5:      if (this.InvokeRequired)

   6:      {

   7:          DelegateManageLink inv = new DelegateManageLink(this.ManageLink);

   8:          this.Invoke(inv, new object[] { url, isEmail });

   9:      }

  10:      else

  11:      {

  12:          if (!string.IsNullOrEmpty(url))

  13:          {

  14:              string tmp = (isEmail == true ? "mailto:" : "") + url;

  15:              System.Diagnostics.Process.Start(tmp);

  16:          }

  17:      }

  18:  }



Sample without parameter:

   1:  /// <summary>

   2:  /// A delegate method to invoke a method and prevent threading concurrent access

   3:  /// </summary>

   4:  private delegate void DelegateCheckServerVersions();

   5:  private void CheckServerVersions()

   6:  {

   7:      if (this.InvokeRequired)

   8:      {

   9:          DelegateCheckServerVersions inv = new DelegateCheckServerVersions(this.CheckServerVersions);

  10:          this.Invoke(inv, new object[] { });

  11:      }

  12:      else

  13:      {

  14:          // your stuff goes here ..

  15:      }

  16:  }

1 comment:

Anonymous said...

Take a look at this book. It has two chapters dedicated to update the UI from independent threads: "C# 2008 and 2005 threaded programming", by Gaston hillar, published by Packt Publishing - www.packtpub.com

http://www.amazon.de/2008-2005-Threaded-Programming-Beginners/dp/1847197108/ref=sr_1_1?ie=UTF8&s=books-intl-de&qid=1233595988&sr=8-1

http://www.packtpub.com/beginners-guide-for-C-sharp-2008-and-2005-threaded-programming/book

It is helping me a lot with the multithreading and multicore jungles.

It provides sample code free to download in Packt's website.

For example, I am using the examples to solve the problem of updating the UI from many independent threads.

Cheers,

Karl (a German developer speaking in english most of the time...)

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge