Skip to content

More on Thread-Safe Invocation

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!

From → miscellaneous

Leave a Comment

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.