C# anonymus delegates efficiency/safety

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;

Answers


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.


Need Your Help

HTTPS Authentication and Cookies via Java

java authentication networking https

I am trying to login and retrieve status information from a HTTPS URL via Java programming. I login through /login.cgi, providing the username and password with a POST request to that script.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.