简体   繁体   English

InvokeAsync订单可靠性

[英]InvokeAsync order reliability

I have a question about invokeAsync and wether the cal order can be taken as reliable ornot. 我有一个关于invokeAsync的问题,是否可以将校准顺序视为可靠还是不可靠。

Example: 例:

//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
    });
}

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? 我可以认为b的InvokeAsync中的代码先在UI线程的分派器中运行是因为b的InvokeAsync是在UI线程的调度程序中首先运行,或者这是大多数情况下b的第一个都将首先运行但在奇怪的情况下运行的情况吗?可能是相反的,或者甚至更糟的是在两者之间跳?

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? 基本上,我可以在某个时候遇到这2次调用吗?还是可以,但是可以肯定地遵循我提到的执行顺序吗? 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类执行以下操作:

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

In this case, the TaskScheduler.FromCurrentSynchronizationContext() option will make the DoSomethingElseWith method run on the UI thread. 在这种情况下, TaskScheduler.FromCurrentSynchronizationContext()选项将使DoSomethingElseWith方法在UI线程上运行。

You may want to look at the Task.ContinueWith Method page on MSDN. 您可能需要查看MSDN上的Task.ContinueWith方法页面。

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

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