Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution order of asynchronously invoked methods

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 ?

like image 580
marc wellman Avatar asked Jun 08 '12 17:06

marc wellman


1 Answers

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.

like image 113
Reed Copsey Avatar answered Sep 23 '22 01:09

Reed Copsey