views:

69

answers:

2

Hello

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;
+6  A: 

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 this or any captured variables) - that may help marginally (but not enough to get excited about)

I would use an anonymous method when:

  • it is short and is logically related to the code that inits the anonymous method
  • it perhaps uses additional context (captured variables) that are tricky to pass into myMethod

The 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 myMethod apprach.

Marc Gravell
+2  A: 

The performance is identical. An anonymous delegate is converted by the compiler into a regular method like any other. If you ILDSM the code you'll see that a real (but hidden) name is generated for the anonymous method.

Brent Arias