Search code examples
wpfsynchronizationcontext

How to "restore" SynchronizationContext when using custom startup?


My app works fine, but now I wanted to have custom startup, so I could catch any errors, add my logging from the start, etc.

So I used approach as shown in this answer What code controls the startup of a WPF application?

[STAThread]
public static void Main(string[] args) {
    //include custom startup code here

    var app = new MyApplication();//Application or a subclass thereof
    var win = new MyWindow();//Window or a subclass thereof
    app.Run(win); //do WPF init and start windows message pump.
}

It works fine with one exception -- SynchronizationContext.Current is null. And I need it :-)

So how to correctly make custom startup and have synchronization context?


Solution

  • Don't create your own Main method. Override the OnStartup method in your App.xaml.cs file:

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
    
            var win = new MyWindow();
            win.Show();
        }
    }
    

    Then you will get a SynchronizationContext as usual.

    Don't forget to remove the StartupUri attribute from the <Application> root element of your App.xaml file.