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); });
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With