Execution order of asynchronously invoked methods

begininvoke, c#, dispatcher, invoke, multithreading

Solution

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.

Problem

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 ?

Original source