Search code examples
c#wpfasync-awaitapp.xamlapp-startup

Async OnStartup in a WPF application


I have a WPF application. If it is started with some command line parameter, it should only do some database operations and then close itself. This is done in the App.xaml.cs:

public partial class App : Application
{
  protected override async void OnStartup(StartupEventArgs e)
  {
    base.OnStartup(e);
    if(Environment.GetCommandLineArgs().Any(x => x == "blabla"))
    {
      await PerformDatabaseOperations()
      Environment.Exit(0);   
    }
    
    var mainWindow = new MainWindow();
    mainWindow.Show();
    this.MainWindow = mainWindow;
  }
}

The problem with this code is that the method PerformDatabaseOperations() is not executed completely. The moment it hits the first actual database operation, the program exits. I assume this is because OnStartup doesn't return a Task and thus can't be awaited. Because of this, the line Environment.Exit(0); is executed when the first asynchronous operation is encountered inside this method.

Is there a way to fix this?


Solution

  • You can call async Methods from within a synchronous method like this:

    YourAsyncMethod().Wait();
    

    So you can make your OnStartup-Method synchronous and perform your database operations like this:

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        if(Environment.GetCommandLineArgs().Any(x => x == "blabla"))
        {
            PerformDatabaseOperations().Wait();
            Environment.Exit(0);   
        }
    
        var mainWindow = new MainWindow();
        mainWindow.Show();
        this.MainWindow = mainWindow;
    }