Working constantly with LINQ and .NET 3.5 these days, I sometimes forget how to do things without lamda expressions. Today, I was working on a WinForms application and I needed to update the UI from a separate thread, so I wrote the following code:
this.BeginInvoke( ()=>
{
//code to update UI
});
This gave me the following error:
Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
I, then tried the anonymous delegate syntax:
this.BeginInvoke( delegate ()
{
//code to update UI
});
Still incorrect, as it gave me this error:
Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type
A quick google revealed that Control.Invoke and Control.BeginInvoke take a System.Delegate as parameter that is not a delegate type and we need to cast our lambas or anonymous delegates to MethodInvoker or Action like this:
this.BeginInvoke( (Action) (()=>
{
this.txtLongestWord.Text = this.longestWord;
}));
The above code does not look good due to lot of brackets, so let’s use the anonymous delegate syntax:
this.BeginInvoke( (Action) delegate ()
{
//code to update UI
});
//or
this.BeginInvoke( (MethodInvoker) delegate ()
{
//code to update UI
});