I have progress form which delegate:
// in ProgressForm thread
public delegate void executeMethod(object parameters);
private executeMethod method;
public object parameters;
// ...
private void ProgressForm_Shown(object sender, EventArgs e)
{
method.Invoke(parameters);
}
Which way is better (mor efficient or safe) to apply – anonymus delegates call like this:
// in other thread
ProgressForm progress = new ProgressForm();
progress.ExecuteMethod = delegate
{
// to do
}
or using separate method like this:
// in other thread
private void myMethod(object par)
{
// to do
}
progress.ExecuteMethod = this.myMethod;
Ultimately they are surprisingly similar; simply, the compiler creates the hidden method internally for the anonymous case. There is no specific performance difference, although there are cases when it might choose to create a static method (if it doesn’t use
thisor any captured variables) – that may help marginally (but not enough to get excited about)I would use an anonymous method when:
myMethodThe main thing to watch is the notorious
foreach(typically) captured variable gotcha, but in some cases it is also possible to bleed a reference into the anonymous method, extending the life-time of a big object unexpectedly.For longer work, I would use the
myMethodapprach.