Control.Invoke without explicit delegates

Calling Control.Invoke tends to be a problem, especially for developers who are new to the .NET world.  I think the primary struggle is how to call Invoke without writing a custom delegate, creating a member variable and/or some helper methods.  Here are a couple patterns that I use pretty regularly:

Using an anonymous delegate

if (this.InvokeRequired)
{
   this.Invoke(new EventHandler( delegate (object o, EventArgs a)
   {
     // do your work here
   }));
}
else
{
  
// do your work here
}

Reusing the existing EventHandler

void MyEventHandler(object sender, EventArgs e)
{
   if (this.InvokeRequired)
   {
     this.Invoke(
       new EventHandler(MyEventHandler), new object[] { sender, e }
     );
     return;
   }

   // do your work here
}

3 thoughts on “Control.Invoke without explicit delegates”

  1. Hy Ctacke
    I think the extension method approach combined with Action delegates is much easier. Consider the following solution:

    How can I post code?

    Then you can easaly write the following code in your Control code:

    How can I post code?

    Daniel

    Like

  2. I use the second technique a lot, it’s a very useful pattern. One thing, though: it’s very easy to forget the "return" in there, causing your method to run twice, once via Control.Invoke then again in the original context. It’s easy to miss this when looking at the code, too.

    Like

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s