Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading