yeeen
yeeen

Reputation: 4945

Why would anyone want to use Invoke() (not BeginInvoke())?

I was told that Invoke() is similar to normal method calling... so why would people 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()?

Upvotes: 1

Views: 1947

Answers (5)

Dave Markle
Dave Markle

Reputation: 97671

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.

Upvotes: 3

Jon Hanna
Jon Hanna

Reputation: 113222

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

Upvotes: 3

vtortola
vtortola

Reputation: 35885

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.

Upvotes: 0

TomTom
TomTom

Reputation: 62093

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 5

Related Questions