简体   繁体   中英

InvokeAsync order reliability

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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