Thursday, February 21, 2008

How to Control.Invoke an Anonymous Method?

Why won't Control.Invoke accept a delegate, even though it's looking for a Delegate?


This might seem like some semantic gymnastics... but when trying to compile this:

this.Invoke(delegate() { MessageBox.Show("Hello"); });


you'll get:

Argument '1': cannot convert from 'anonymous method' to 'System.Delegate'


which would suggest that a delegate is not a Delegate.

It's not exactly so - the problem is actually that the compiler does not know to what particular subtype of System.Delegate to cast/convert the anonymous method (delegate) to - and it can't create an instance of System.Delegate.

To make the code work, you have to explicitly create an instance of a particular type of a parameterless delegate returning void, e.g.:

this.Invoke(new MethodInvoker(delegate() {MessageBox.Show("Hello"); }));



see: Anonymous methods and Control.Invoke

1 comment:

Annie Calvert said...

It is a great tutorial to get know more about how to invoke and increase .net performance. This way of doing it really cleans things up.
http://www.dapfor.com/en/net-suite/net-grid/features/performance