简体   繁体   English

Control.BeginInvoke()和Dispatcher.BeginInvoke()有什么区别?

[英]What is difference between Control.BeginInvoke() and Dispatcher.BeginInvoke()?

Recently I used Control.BeginInvoke() method to put a method call into queue to be called on UI thread later. 最近,我使用Control.BeginInvoke()方法将方法调用放入队列,以便稍后在UI线程上调用。 I also know there is Dispatcher.BeginInvoke() method. 我也知道有Dispatcher.BeginInvoke()方法。 I read some general resources ( like this on CodeProject ) and still have the question whether behavior of Control.BeginInvoke() is different from Dispatcher.BeginInvoke() or not. 我阅读了一些常规资源( 如在CodeProject上这样 ),但仍然有一个问题,即Control.BeginInvoke()行为是否与Dispatcher.BeginInvoke()不同。

I understand that analogical question can be asked for difference between Control.Invoke() and Dispatcher.Invoke() . 我知道可以问类比问题,以获取Control.Invoke()Dispatcher.Invoke()之间的区别。

Control.BeginInvoke existed from the early days of .NET (at least version 1.1). Control.BeginInvoke从.NET的早期版本开始存在(至少1.1版)。 This is a very natural fit if you have an control and want to run something on its UI thread (there can be several UI threads ). 如果您有一个控件并且想要在其UI线程上运行某些东西(可以有多个UI线程 ),那么这是非常自然的选择。 However if you wanted to run something general on the UI thread and didn't have an appropriate Control the hacky solution was to create a Control which doesn't appear in the UI and then Invoke on that. 但是,如果您想在UI线程上运行常规操作,并且没有合适的Control那么骇人的解决方案是创建一个不会出现在UI中的Control ,然后在该ControlInvoke

In .NET 3 (IIRC) Dispatcher was added to solve this problem. 在.NET 3(IIRC)中,添加了Dispatcher以解决此问题。

In short: 简而言之:

  • If you have a Control at hand you can use Control.BeginInvoke 如果您有Control ,则可以使用Control.BeginInvoke
  • If you don't have an appropriate control, create a Dispatcher (in advance) and use Dispatcher.BeginInvoke 如果没有适当的控件,请提前创建一个Dispatcher并使用Dispatcher.BeginInvoke
  • If you're in the distant past, you have no option but to use Control.BeginInvoke :) 如果您处于遥远的过去,则只能使用Control.BeginInvoke :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM