【问题标题】:Execution order of asynchronously invoked methods异步调用方法的执行顺序
【发布时间】:2012-06-08 17:09:36
【问题描述】:

当我对 Dispatcher 调用多个方法时,比如说 UI Thread 的 Dispatcher,

喜欢这里

uiDispatcher.BeginInvoke(new Action(insert_), DispatcherPriority.Normal);
uiDispatcher.BeginInvoke(new Action(add_), DispatcherPriority.Normal);
uiDispatcher.BeginInvoke(new Action(insert_), DispatcherPriority.Normal);

这些方法会按照我调用它们的顺序执行吗?

【问题讨论】:

  • 一般来说,写异步代码时,你的代码应该写成调用顺序无关紧要。

标签: c# multithreading invoke dispatcher begininvoke


【解决方案1】:

使用Dispatcher,这些将始终按照它们被调用的顺序执行,但这只是因为DispatcherPriority 是相同的。这是有保证的行为,并记录在 Dispatcher.BeginInvoke:

如果在同一个 DispatcherPriority 上进行了多个 BeginInvoke 调用,它们将按照调用的顺序执行。

话虽如此,对于异步操作,通常最好不要依赖这种行为。如果您将它们称为异步操作,则不应计划按特定顺序执行的事情。这实际上是在您的异步操作和调度程序实现之间创建Coupling

如果顺序确实很重要,那么即使调度机制发生变化,通常最好以能够保证这一点的方式重新设计设计。例如,使用 TPL 时这要简单得多,因为您可以安排操作,然后将后续操作安排为第一个任务的延续。

【讨论】:

  • 删除了我的答案,因为它是不正确,因为我错过了一些重要的东西。这是正确的答案。
  • @Reed Copsey 知道我可以在有意义的情况下利用 Dispatcher 对象的这种特殊行为非常有用。无法依赖异步操作的执行顺序是一种非常令人满意的情况,因为您始终必须自己处理操作的顺序,而不是依赖于一些不可预测的后台执行机制。非常感谢您的回答!
【解决方案2】:

来自MSDN

如果在同一个 DispatcherPriority 上进行了多个 BeginInvoke 调用,它们将按照调用的顺序执行。

【讨论】:

  • 当我查看文档时,我已经监督了这一点 :) 非常感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 2011-08-18
  • 2021-08-11
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多