Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 273
SomeBody Avatar asked Oct 17 '25 09:10

SomeBody


1 Answers

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;
}
like image 189
jeanluc162 Avatar answered Oct 19 '25 22:10

jeanluc162



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!