Event publish order

Sep 15, 2008 at 5:18 PM

The IEventAgregator behavior is very weird. The publishing order seems to be buggy!

The following source code subscribes 2 times with 2 differents handlers to the same event.
With the ThreadOption = UIThread, the published order is: Login1EventHandler then Login2EventHandler.
But with ThreadOption = PublisherThread, the published order is: Login2EventHandler then Login1EventHandler.

Is there a way to control the publishing order?

    public partial class Window1 : Window
        IEventAggregator eventAggregator = new EventAggregator();
        public Window1()
            eventAggregator.GetEvent<LoginEvent>().Subscribe(Login1EventHandler, ThreadOption.UIThread);
            eventAggregator.GetEvent<LoginEvent>().Subscribe(Login2EventHandler, ThreadOption.UIThread);

        private void button1_Click(object sender, RoutedEventArgs e)

        void Login1EventHandler(string o)
        void Login2EventHandler(string o)
    public class LoginEvent : CompositeWpfEvent<string>{}

Sep 16, 2008 at 3:19 PM
Edited Sep 16, 2008 at 3:20 PM

The current implementation of the Event Aggregation service uses a List<IEventSubscription> collection to store the event subscriptions. Every time that you add new subscription, this is added to the end of the collection. When the event is published, the Subscriptions collection is iterated from the end to the beginning. So the last event subscription is usually the first to be published.

However the execution order of the subscriptions is not guaranteed. For example is you subscribe to an event in the UIThread you could not be sure when the event will be executed (the event is executed asynchronously using the BeginInvoke method of the Dispatcher).

You should not be dependant of the execution order of the events. If you need to specify a predefined order, you could chain the event subscriptions/publications in different events (i.e. PreLoginEvent, PostLoginEvent).

You should also note that you should not modify the payload and assume that it will be modified when it reaches the next subscriber or when execution returns to the publisher, as the approach of the Event Aggregation service is Fire-and-forget (specifically if you dispatch on something different than the publisher thread, these will be invoked asynchronically).

Please, let me know if it helps.

Mariano Converti

Sep 25, 2008 at 9:54 AM
I do not understand why the UIDispatcher is not able to dispatch the event in the publishing order since there is only one UIDispatcher (=Application.Current.Dispatcher) in the whole application.
But thank you very much for your answer.