Showing posts with label Windows Forms. Show all posts
Showing posts with label Windows Forms. Show all posts

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

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