Anonymous methods and Delegates
by Alec Horn on Sep.21, 2009, under .NET/C#, Coding
So, I’m currently working on a Windows forms application built by a coworker and adding some threading to it to provide a more enhanced interface.
Of course we come into the issue of thread locking, and of course Invoke must be used. We’re in .NET 3.5, might as well get some of the benefits of the latest framework, right? Well, turned out to be a bit more confusing than I first thought.
Ex:
delegate bool GetBoolDelegate();
int GetBoolValue()
{
if (!InvokeRequired)
return (bool)vart.SelectedIndex;
else
return (bool)Invoke(new GetBoolDelegate(GetBoolValue), null);
}
The pre 2.0 way of doing things, move along and try:
bool regchecked = (bool)this.Invoke(
delegate()
{
return chkRegression.Checked;
}
);
Which gives the following error:
Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type
There are several ways around this, the easiest is:
public delegate bool MethodBoolInvoke();
bool regchecked = (bool)this.Invoke(
(MethodBoolInvoke)delegate()
{
return chkRegression.Checked;
}
);
And, the final simple example of invoking for general items:
this.Invoke( (MethodInvoker)delegate() {this.Cursor = Cursors.WaitCursor; });