Entries
RSS 2.0

Comments
RSS 2.0

More on Thread-Safe Invocation

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:

   1: public static class ThreadSafe
   2: {
   3:   public static void Invoke(ISynchronizeInvoke context, MethodInvoker method)
   4:   {
   5:     if (context.InvokeRequired)
   6:       context.Invoke(method);
   7:     else
   8:       method();
   9:   }
  10: }

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

   1: public class MyForm : Form
   2: {
   3:   public void SetMessage(string message)
   4:   {
   5:     ThreadSafe.Invoke(this, delegate
   6:     {
   7:       this.lblMessage.Text = message;
   8:     });
   9:   }
  10: }

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!

Leave a comment

Please be polite and on topic. Your e-mail will never be published.