Execution order of asynchronously invoked methods
Asked Answered
C

2

5

When I am invoking a number of methods to a Dispatcher, say the Dispatcher of the UI Thread,

like here

uiDispatcher.BeginInvoke(new Action(insert_), DispatcherPriority.Normal);
uiDispatcher.BeginInvoke(new Action(add_), DispatcherPriority.Normal);
uiDispatcher.BeginInvoke(new Action(insert_), DispatcherPriority.Normal);

will those methods be executed in the same order as I have invoked them ?

Canned answered 8/6, 2012 at 17:9 Comment(1)
Generally speaking, when writing asynchronous code, your code should be written in such a way that the order of invocation does not matter.Outoftheway
A
11

With the Dispatcher, these will alway execute in the same order in which they were called, but only because the DispatcherPriority is the same. This is guaranteed behavior, and documented in Dispatcher.BeginInvoke:

If multiple BeginInvoke calls are made at the same DispatcherPriority, they will be executed in the order the calls were made.

That being said, with asynchronous operations, it's typically better to not rely on this behavior. You shouldn't plan on things executing in a specific order if you're calling them as asynchronous operations. This effectively is creating Coupling between your asynchronous operations and your scheduler implementation.

If order does matter, then it's typically better to rework the design in a manner which guarantees this, even if the scheduling mechanism were to change. This is far simpler using the TPL, for example, as you can schedule operations, and then schedule the subsequent operations as continuations of the first task.

Andromeda answered 8/6, 2012 at 17:13 Comment(2)
deleted my answer because it was incorrect due to my missing something important. This is the correct answer.Phantasmagoria
@Reed Copsey It's very useful to know that I can take advantage of this particular behavior of the Dispatcher object when it makes sense. To be unable to rely on the order of executions of asynchronous operations is a very satisfying situation since you always have to take care of the order of your operation on your own instead as relying to some unpredictable execution mechanism in the background. Thank you very much for your answer!Canned
M
5

From MSDN

If multiple BeginInvoke calls are made at the same DispatcherPriority, they will be executed in the order the calls were made.

Minica answered 8/6, 2012 at 17:14 Comment(1)
I have overseen that as I took a look into the documentation :) Thank you very much for your answer.Canned

© 2022 - 2024 — McMap. All rights reserved.