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?
The . NET Framework has full support for running multiple threads at once.
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.
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.
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