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 });
Note that the same syntax holds for Dispatcher’s Invoke or BeginInvoke method that can be used in WPF to marshall calls on the UI thread.
November 24, 2009 at 1:32 AM
Control.Invoke and BeginInvoke using lamba and anonymous delegates « Mehroz’s Experiments…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
December 13, 2013 at 1:58 AM
also, if you need to return values, use Func like below
if (frm.InvokeRequired)
{
DialogResult res = (DialogResult)frm.Invoke(new Func(()=>MessageBox.Show(frm, “some msg”, “InvokeRequired”)));
}
else
MessageBox.Show(frm, some msg”, “not required”);
September 21, 2014 at 2:41 AM
I have been exploring for a bit for any high quality articles or weblog posts in this kind of space .
Exploring in Yahoo I finally stumbled upon this site.
Reading this information So i’m glad to exhibit that I have a very just right uncanny
feeling I found out just what I needed. I so much undoubtedly
will make certain to don?t put out of your mind this
web site and provides it a look on a continuing basis.
November 19, 2014 at 5:09 AM
Thanks for sharing your experiance I did realy have same problem.
September 4, 2015 at 5:42 PM
Thank You…
August 14, 2019 at 1:19 PM
[…] Buen post relacionados: smehrozalam.wordpress.com/2009/11/24/… […]