delegate void DelegateTest(); DelegateTest delTest;
Whats the difference between calling delTest.Invoke()
and delTest()
? Both would execute the delegate on the current thread, right?
A delegate instance encapsulates an invocation list, which is a list of one or more methods, each of which is referred to as a callable entity. For instance methods, a callable entity consists of an instance and a method on that instance. For static methods, a callable entity consists of just a method.
BeginInvoke : Executes asynchronously, on a threadpool thread. Control. Invoke : Executes on the UI thread, but calling thread waits for completion before continuing.
The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception.
A delegate is a method with a parameter and a return type. A delegate is a type that safely encapsulates a method. Delegates are object-oriented, type safe, and secure.
The delTest()
form is a compiler helper, underneath it is really a call to Invoke()
.
Richard's answer is correct, however starting with C# 6.0, there is one situation where using Invoke()
directly could be advantageous due to the addition of the null conditional operator. Per the MS docs:
Another use for the null-conditional member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:
var handler = this.PropertyChanged; if (handler != null) handler(…);
The new way is much simpler:
PropertyChanged?.Invoke(…)
The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in a temporary variable. You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e).
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