0

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?

537mfb
  • 1,374
  • 1
  • 16
  • 32

1 Answers1

0

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.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • Not sure what your filePath is there but will look at task - that sort is the same as copying the code from the invoke in a to the end of the invoke in b no? – 537mfb Oct 11 '13 at 14:26
  • It was just showing you that you can use local variables in these methods, but I probably should have mentioned that. No, not really... the first part will run asynchronously and using the `TaskScheduler.FromCurrentSynchronizationContext()` option will make the second part run on the UI thread. Even if you left that option off, it's still not the same because they would run in different asynchronous contexts, but the second part would just wait for the first to complete. – Sheridan Oct 11 '13 at 14:31
  • I ended up doing some refactoring that did away wth the issue but this is the answer i was looking for before the refactoring - thanks – 537mfb Oct 14 '13 at 18:09