InvokeAsync订单可靠性 [英] InvokeAsync order reliability

查看:137
本文介绍了InvokeAsync订单可靠性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于invokeAsync的问题,是否可以将校准顺序视为可靠.

I have a question about invokeAsync and wether the cal order can be taken as reliable ornot.

示例:

//Get Dispatcher of UI Thread
private Dispatcher _dsp = Dispatcher.CurrentDispatcher;

//Method called from non-UI Thread
private void a() {
    //Do Stuff
    b();
    _dsp.InvokeAsync(() => {
          //Do Stuff in UI Thread
    });
}

private void b() {
    //Do stuff
    _dsp.InvokeAsync(() => {
        //Do stuff in UI Thread
    });
}

我是否可以认为b的InvokeAsync中的代码将在a'InvokeAsync中的代码之前运行,因为它首先放在UI Thread的分派器中?还是在这种情况下,大多数情况下b的代码将首先运行但在奇怪的情况可能是相反的,甚至更糟糕的是,两者之间跳了起来?

Can i take for granted that the code in b's InvokeAsync will be ran before the code in a' InvokeAsync since it's put in the UI Thread's dispatcher first or is this a case where most of the time b's will be ran first but on odd circustances it might be the other way around, or even worse, jump betwee the two?

基本上,我是否可以在某些时候遇到这2次调用,或者此确定可以可靠地遵循我提到的执行顺序?如果有问题的机会,关于如何使其变得更好的任何想法?

Basicly, could i have trouble with this 2 Invokes at some point or is this ok nad will reliably follow the execution order i mentioned? If there's a chance on problema, any ideas on how to make it good?

推荐答案

我不认为您可以对任何异步操作的运行顺序做出任何假设.但是,如果需要它们按顺序运行,则可以使用

I don't believe that you can make any assumptions about the order that any asynchronous operations will run. However, if you need them to run in sequence, you can use the Task class to do something like this:

Task.Factory.StartNew(() => DoSomethingWith(filePath)).ContinueWith((
    Task resultFromPrevious) => DoSomethingElseWith(resultFromPrevious),  
    TaskScheduler.FromCurrentSynchronizationContext())

在这种情况下,TaskScheduler.FromCurrentSynchronizationContext()选项将使DoSomethingElseWith方法在UI线程上运行.

In this case, the TaskScheduler.FromCurrentSynchronizationContext() option will make the DoSomethingElseWith method run on the UI thread.

您可能希望查看任务MSDN上的.ContinueWith Method 页面.

这篇关于InvokeAsync订单可靠性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆