More on Thread-Safe Invocation

by Nate on August 13, 2007

In my last post a few days ago, I described a simple trick for creating thread-safe wrappers for event handlers in WinForms controls. I’ve discovered an even simpler approach that is much more general-purpose:

public static class ThreadSafe
{
  public static void Invoke(ISynchronizeInvoke context, MethodInvoker method)
  {
    if (context.InvokeRequired)
      context.Invoke(method);
    else
      method();
  }
}

Then, in your control, you can define methods like this:

public class MyForm : Form
{
  public void SetMessage(string message)
  {
    ThreadSafe.Invoke(this, delegate {
      this.lblMessage.Text = message;
    });
  }
}

Through the magic of variable capturing with anonymous methods, you don’t need to pass the arguments into your inner method (the delegate that you’re passing to the Invoke method). This also means that the Invoke method can be used to protect methods with any signature. Be aware, though, that the captured variables are read-only in the inner context. (More information about captured variables and the difference between lexical closures in C# and Ruby is available here.)

I haven’t given this too much testing so far, but it seems to work!

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • FriendFeed
  • HackerNews
  • Posterous
  • Reddit
  • Twitter

Related posts:

  1. Thread Safe Event Handlers
  2. Fast Late-Bound Invocation with Expression Trees
  3. Functional Magic

Leave a Comment

Previous post: Thread Safe Event Handlers

Next post: Defending Dependency Injection