Control.Invoke and BeginInvoke using lamba and anonymous delegates

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.

6 Responses to “Control.Invoke and BeginInvoke using lamba and anonymous delegates”

  1. DotNetShoutout Says:

    Control.Invoke and BeginInvoke using lamba and anonymous delegates « Mehroz’s Experiments…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. dmihailescu Says:

    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”);

  3. Tony Bennett Lady Gaga Cheek to Cheek leaked album Says:

    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.

  4. Xusan Says:

    Thanks for sharing your experiance I did realy have same problem.

  5. Armugam Says:

    Thank You…

  6. anonymous-methods - Anónimo método como parámetro a BeginInvoke? Says:

    […] Buen post relacionados: smehrozalam.wordpress.com/2009/11/24/… […]


Leave a comment