Wednesday, October 7, 2015

Dispatcher Await execution order

<Window x:Class="WpfApplication9.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Button HorizontalAlignment="Center" VerticalAlignment="Center"
            Content="Start" Click="StartButton_OnClick"/>
</Window>
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace WpfApplication9
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void StartButton_OnClick(object sender, RoutedEventArgs e)
        {
            new Thread(ThreadStart).Start();
        }

        static void ThreadStart()
        {
            var disp = Dispatcher.CurrentDispatcher;

            disp.BeginInvoke(new Action(LowPriority),
                DispatcherPriority.Background);

            disp.BeginInvoke(new Action(Delay),
                DispatcherPriority.Input);

            disp.BeginInvoke(new Action(Sleep),
                DispatcherPriority.Input);

            disp.BeginInvokeShutdown(
                DispatcherPriority.Input);

            Dispatcher.Run();
            MessageBox.Show("4. Shutdown");
        }

        static void LowPriority()
        {
            MessageBox.Show("3. LowPriority");
        }

        static async void Delay()
        {
            await Task.Delay(500);
            MessageBox.Show("2. Delay");
        }

        static void Sleep()
        {
            Thread.Sleep(1000);
            MessageBox.Show("1. Sleep");
        }
    }
}