Cleanest Way to Invoke Cross-Thread Events Cleanest Way to Invoke Cross-Thread Events multithreading multithreading

Cleanest Way to Invoke Cross-Thread Events


I have some code for this online. It's much nicer than the other suggestions; definitely check it out.

Sample usage:

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args){    // You could use "() =>" in place of "delegate"; it's a style choice.    this.Invoke(delegate    {        // Do the dirty work of my method here.    });}


A couple of observations:

  • Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use:
   BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent),                sender,                args);
  • Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list.

  • I would probably favor Invoke over BeginInvoke as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to EndInvoke. What would happen is that your app will end up getting a TargetInvocationException instead.


I shun redundant delegate declarations.

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args){    if (InvokeRequired)    {        Invoke(new Action<object, CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args);        return;    }    // do the dirty work of my method here}

For non-events, you can use the System.Windows.Forms.MethodInvoker delegate or System.Action.

EDIT: Additionally, every event has a corresponding EventHandler delegate so there's no need at all to redeclare one.