Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Delegate.Invoke and Delegate()

Tags:

c#

delegates

delegate void DelegateTest();  DelegateTest delTest; 

Whats the difference between calling delTest.Invoke() and delTest()? Both would execute the delegate on the current thread, right?

like image 804
remdao Avatar asked Sep 02 '09 11:09

remdao


People also ask

What is invoke delegate?

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.

What is difference between Invoke and BeginInvoke?

BeginInvoke : Executes asynchronously, on a threadpool thread. Control. Invoke : Executes on the UI thread, but calling thread waits for completion before continuing.

Why we use invoke in C#?

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.

What is difference between delegate and method in C#?

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.


2 Answers

The delTest() form is a compiler helper, underneath it is really a call to Invoke().

like image 89
Richard Avatar answered Oct 13 '22 11:10

Richard


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).

like image 36
iliketocode Avatar answered Oct 13 '22 12:10

iliketocode