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
overBeginInvoke
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 toEndInvoke
. What would happen is that your app will end up getting aTargetInvocationException
instead.