本文介绍了Invoke()和BeginInvoke()有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道BeginInvoke()Invoke()之间的区别是什么?

Just wondering what the difference between BeginInvoke() and Invoke() are?

主要是每个人的用途.

创建线程对象并在该对象上调用invoke和仅在委托上调用BeginInvoke()之间有什么区别?还是他们是同一回事?

What is the difference between creating a threading object and calling invoke on that and just calling BeginInvoke() on a delegate? or are they the same thing?

推荐答案

您是说Delegate.Invoke/BeginInvoke还是Control.Invoke/BeginInvoke?

  • Delegate.Invoke:在同一线程上同步执行.
  • Delegate.BeginInvoke:在threadpool线程上异步执行.
  • Control.Invoke:在UI线程上执行,但是调用线程在继续之前等待完成.
  • Control.BeginInvoke:在UI线程上执行,并且调用线程不等待完成.
  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

蒂姆的答案提到了您可能想使用BeginInvoke的时间-我怀疑,尽管它主要是针对Delegate.BeginInvoke的.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

对于Windows Forms应用程序,我建议您通常使用BeginInvoke.这样,您就不必担心死锁了-但是您需要了解,在下次查看UI时可能尚未更新UI!特别是,您不应修改UI线程可能要用于显示目的的数据.例如,如果您有一个具有FirstNameLastName属性的Person,并且您做到了:

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

然后,UI可能最终会显示"Keyser Spacey". (有外部机会显示"Kevin Soze",但只能通过内存模型的怪异来显示.)

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

但是,除非您遇到此类问题,否则Control.BeginInvoke更容易解决,并且可以避免后台线程无缘无故地等待.请注意,Windows Forms团队已保证您可以发射后忘记"的方式使用Control.BeginInvoke-即,无需调用EndInvoke.一般来说,异步调用不是这样:通常每个BeginXXX应该在回调中都有一个对应的EndXXX调用.

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

这篇关于Invoke()和BeginInvoke()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:34