John Smith John Smith - 1 year ago 72
C# Question

What's the difference between "call" and "invoke"?

I'm currently reading a book by Daniel M. Solis called "Illustrated C# 2010." The book says:

"When a method is called or invoked ..."

What is the difference between these two terms?

Answer Source

Ultimately they are identical. The difference is in performance and benefits. If you directly call a method then the compiler will generate the necessary code to look up the method start address in the object's virtual table, push the parameters onto the stack and invoke the method. The runtime is ultimately responsible for dealing with this because a vtable can change depending on the object being used. Highly optimized and very fast given modern processors. This is the ideal mechanism to use. The problem is that you must know at compilation time the type being referenced, the method name and its signature. This is formally known as early binding. If the method information changes then your code won't compile. Normally this is no problem but sometimes it is important. This is where invoke comes in.

Invoke is commonly used in UI code. In UI code a fundamental rule of Windows is that you can only interact with the UI on the thread that created the UI. Therefore if you want to talk with the UI on a secondary thread (such as a worker thread) you must marshal the call to the correct thread. Note that this applies to events as well. They are really nothing more than method invocations. The Control.Invoke method that is inherited by all WinForm controls allows you to call an arbitrary method on the UI thread. The method handles the process of marshalling the request to the correct thread and then calling Invoke on the method. This is still late-binding even though you know in advance what method you wanted to call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download