gpt4 book ai didi

c# - 异步调用方法的执行顺序

转载 作者:太空狗 更新时间:2023-10-29 22:11:02 24 4
gpt4 key购买 nike

当我调用一些方法给一个 Dispatcher 时,比如说 UI 线程的 Dispatcher,

喜欢这里

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

这些方法的执行顺序是否与我调用它们的顺序相同?

最佳答案

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

If multiple BeginInvoke calls are made at the same DispatcherPriority, they will be executed in the order the calls were made.

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

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

关于c# - 异步调用方法的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10953161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com