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

浪尽此生 提交于 2020-01-15 12:39:27

问题


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()?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/3940934/why-would-anyone-want-to-use-invoke-not-begininvoke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!