InvokeAsync order reliability

一世执手 提交于 2020-01-06 07:17:44

问题


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

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?

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?


回答1:


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())

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

You may want to look at the Task.ContinueWith Method page on MSDN.



来源:https://stackoverflow.com/questions/19315744/invokeasync-order-reliability

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!