Monday, February 3, 2014

WPF Dispatcher execution order

using System;
using System.Windows.Threading;

namespace ConsoleApplication7
{
    class Program
    {
        private static void Main(string[] args)
        {
            var dispatcher = Dispatcher.CurrentDispatcher;
            Action a1 = () =>
            {};
            Action a2 = () =>
            {};
            Action a3 = () =>
            {};
            // a1 is pushed onto the Input queue
            dispatcher.BeginInvoke(a1, DispatcherPriority.Input);
            // a2 is pushed onto the Normal queue
            dispatcher.BeginInvoke(a2, DispatcherPriority.Normal);
            // a3 is pushed onto the Normal queue
            // a2 is popped and executed
            // a3 is popped and executed
            dispatcher.Invoke(a3, DispatcherPriority.Normal);
            // a1 is popped and executed
            // then the thread sleeps waiting for the queues
            Dispatcher.Run();
        }
    }
}