何时执行Dispatcher.Invoke中的代码?

时间:2013-03-02 12:37:47

标签: c# wpf multithreading dispatcher

在C#WPF项目中,我有一个后台线程需要刷新一些UserControls。 为此,我使用了Dispatcher.Invoke:

    Dispatcher.Invoke(DispatcherPriority.Normal, (MethodInvoker)delegate()
    {
        // Code
    }

但我想知道:

  • 何时代理内的代码将在主线程上执行?
  • 要执行它,可以停止正常在主线程上运行的方法吗?
  • 使用Dispatcher.Invoke会导致竞争条件吗?

非常感谢, Emanuele的

2 个答案:

答案 0 :(得分:2)

  

何时代理中的代码将在主线程上执行?

如果所有operations with priority greater than Normal got a chance to execute

,则委托将在主线程上执行一次
  

要执行它,通常在主线程上运行的方法可以是   停止?

Invoke方法使委托在主线程上同步执行,但如果要异步执行,则需要使用BeginInvoke。如果某个委托在主线程上运行,则为delegate will get queued and will run once executing operation gets completed。但是,除非委托被执行,否则后台线程将不会继续前进。

  

使用Dispatcher.Invoke会导致竞争条件吗?

No,因为委托在Dispatcher Queue中排队,所以不会。

答案 1 :(得分:0)

  1. 当UI线程能够在SynchronizationContext.Send调用时切换执行时。
  2. 执行时,通常在主线程上运行的方法将完成运行(包括其他伪非完成条件,如yieldawait),然后运行您的函数。< / LI>
  3. 没有