Control.Invoke and anonymous methods

L

Lee Crabtree

I'm a little confused about using Control.Invoke with an anonymous
method. It seems like the compiler is able to generate whatever glue
code is necessary to turn an anonymous method into a delegate type in
several situations, such as starting a thread:

Thread workerThread = new Thread(delegate { MessageBox.Show("Hello!"); });

However, trying to do the same thing with a form, as in:

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

nets an error stating that an anonymous method is not a delegate type,
and can't be converted. It's easy enough to wrap the anonymous method
in a MethodInvoker or whatever other required delegate type, but I don't
really understand why the difference exists at all.

Lee Crabtree
 
P

Patrick Steele

I'm a little confused about using Control.Invoke with an anonymous
method. It seems like the compiler is able to generate whatever glue
code is necessary to turn an anonymous method into a delegate type in
several situations, such as starting a thread:

Thread workerThread = new Thread(delegate { MessageBox.Show("Hello!"); });

However, trying to do the same thing with a form, as in:

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

nets an error stating that an anonymous method is not a delegate type,
and can't be converted. It's easy enough to wrap the anonymous method
in a MethodInvoker or whatever other required delegate type, but I don't
really understand why the difference exists at all.

The Thread ctor accepts a specific type of delegate (ThreadStart). If
your anonymous method matches the signature of the delegate, the
compiler can do the work of inferring the type.

But Control.Invoke accepts any Delegate-derived type. The signature for
your anonymous method (void return type and no parameters) could match
any number of Delegate-derived types. Which one should the compiler
use? There's no way to infer that automatically.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top