Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms multithreading: Is creating a new delegate each time when invoking a method on the UI thread needed?

I want to invoke a method that manipulates a control on the UI thread. My code works and I want to optimize. I am referring to this resource on MSDN.
According to there, we should do

public delegate void myDelegate(int anInteger, string aString);
//...
Label1.Invoke(new myDelegate(myMethod), new Object[] {1, "This is the string"});

Would this introduce an orphaned delegate object (a memory leak), at each call?

When I would do it with a static instance of the delegate like below and then use this instance at each call to invoke:

private static _delegateInstance = new myDelegate(myMethod);
//...
Label1.Invoke(_delegateInstance , new Object[] {1, "This is the string"});

Would this be Thread-Safe? I would it be true that this has a slightly better performance, since the delegate instance is only created once?

like image 890
Marcel Avatar asked Nov 26 '10 08:11

Marcel


People also ask

Is Winforms multithreaded?

The . NET Framework has full support for running multiple threads at once.

How do you call a delegate in C#?

Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.


1 Answers

The two answers above have given some insight. There is a good article here if you want to get some more in depth information.

Both methods are thread safe, because at invoke time the thread pool allocates a thread for each call. There is the potential for locking, but if you read that article there are ways around that.

Also, you need to keep in mind that .Net handles the UI thread slightly differently. If you are dealing with WPF, you'll have to take the dispatcher into consideration. See here.

Ultimately, I'm not sure you would gain a massive performance increase with the second piece of code, so I'd be inclined to stick with the first.

N.

like image 107
Nick Avatar answered Sep 22 '22 11:09

Nick