views:

102

answers:

5

I was told that Invoke() is similar to normal method calling... so why would ppl choose to use Invoke and not normal method calling?

I tried to search online regarding the issue, what i get is the advantages of using BeginInvoke(), but what are the advantages of using Invoke()?

Thanks

+3  A: 

Use BeginInvoke when you want to call the delegate asynchronously (on a thread drawn from the thread pool) and Invoke if you want to call it synchronously.

Darin Dimitrov
when you use BeginInvoke the ThreadPool is used witch is not recommended for long running procedures...
Petoj
+3  A: 

One reason is if you've gotten your method signature through reflection and you dynamically want to instantiate a function, Invoke() is the way you'd do that.

Dave Markle
A: 

In order to change, for example, the thread executing something.

Note that any UI control shall and can alweays only be manipulated from the thread that created it (message pump, actually). So, if another thread is manipulating the control (synchronously from that other threads point of view) then BeginInvoke would be additional overhead, but Invoke is fine (ESPECIALLY because at least in WPF there is a shortcut herere for multiple invoke sequences that make it faster to execute internally).

TomTom
A: 

I guess you already understand what a delegate is, what is for, and why is useful.

If I have a deletegate named "MyDelegate", I can do "MyDelegate(foo);" or "MyDelegate.Invoke(foo);" , but I always use the second one so I could easily see when I review the code, that is actually a delegate and not a method. There is no internal difference.

vtortola
Did you know that you don’t need to put the extra “Invoke” to know that it’s a delegate and not a method? You can just hover your mouse over it, or press F12 on it.
Timwi
I know :D But I want to realize that just reading quicly the code :)
vtortola
+2  A: 

It's worth noting first that we have to have something like .Invoke() as the meeting-point between languages. Just as what is int to C# and Integer to VB.NET is System.Int32 to both of them, and to any other CLR language; so too we have Invoke() which any CLR language can offer access to, and which they can then provide additional syntactic sugar in a means suitable for their syntax (most would consider heavily VB style conventions in C# or heavily C# style conventions in VB to be syntactic vinegar; sugar always has to match the rest of the language as best it can).

This sugar added, why not use it all the time? Some people will sometimes want to be clear that they are dealing with a delegate. Some just won't use it; I mostly don't. Like all syntactic sugar, the advantages and disadvantages are matters of clarity rather than correctness (indeed, look at a call to x.Invoke() in reflector and you'll see that it as x() because reflector doesn't know which you used).

Jon Hanna