Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous methods and delegates

I try to understand why a BeginInvoke method won't accept an anonymous method.

void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (InvokeRequired)
    {
        //Won't compile
        BeginInvoke(delegate(object sender, ProgressChangedEventArgs e) 
        { bgWorker_ProgressChanged(sender, e); });
    }

    progressBar1.Increment(e.ProgressPercentage);
}

It tells me 'cannot convert from 'anonymous method' to 'System.Delegate' while when I cast the anonymous method to a delegate it does work ?

BeginInvoke((progressDelegate)delegate { bgWorker_ProgressChanged(sender, e); });
like image 833
Mez Avatar asked Jun 09 '09 07:06

Mez


People also ask

What are anonymous methods?

Anonymous method is a block of code, which is used as a parameter for the delegate. An anonymous method can be used anywhere. A delegate is used and is defined in line, without a method name with the optional parameters and a method body. The scope of the parameters of an anonymous method is the anonymous-method-block.

What are anonymous delegates in C#?

C# - Anonymous Method As the name suggests, an anonymous method is a method without a name. Anonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type. Example: Anonymous Method.

What is diff between delegate anonymous method and lambda expression?

Anonymous Method is an inline code that can be used wherever a delegate type is expected. Microsoft introduced Anonymous Methods in C# 2.0 somewhere around 2003. Lambda expression is an anonymous method that you can use to create delegates or expression tree types.

What are delegate methods?

A delegate method is a method that the delegate object is expected to implement. Some delegate methods are required, while some are not. In IOS, most delegates are expected to conform to an Objective-C protocol; the protocol declaration will tell you which methods are optional and which are required.


1 Answers

You need to tell the compiler what type of delegate to create, since Invoke (etc) just take Delegate (rather than something more specific).

To apply to the largest audience, MethodInvoker is a handy delegate type

BeginInvoke((MethodInvoker) delegate(...) {...});

However... BackgroundWorker.ProgressChanged fires on the UI thread automatically - so you don't even need this.

like image 54
Marc Gravell Avatar answered Oct 04 '22 07:10

Marc Gravell