简体   繁体   中英

Wait for WinForms async method to return before closing

I have a WinForms app that looks up some data from tables and sends out said data to an external API via HTTP. In the app I display a data grid that lists the rows that contain the data sent via the API.

I would like to have the application exit itself after it is done sending the data via the HTTP API. How do I wait for the asynchronous method GetEventData to finish executing before having the program shut itself down?

public Main()
{
  InitializeComponent();

  GetEventData();

  // Exit the app
  Environment.Exit(-1);
}

The method that calls the API is below (entire method not shown just await portion)

private async void GetEventData()
{ 
  \\ Get data from database code before here

  ClientDataObject client = new ClientDataObject();
  apiResult = await client.SendDataVia API(); 

  // Update the grid with list of rows that were sent to API
  UpdateGridView();
}

Currently, the application starts and then exists right away. I believe this is because the GetEventData method is not blocking the rest of the code. I am using async and await so the GUI remains responsive (able to display state of data in database) while waiting for the API calls to complete

The async method shouldn't be void . You should only have an async void method when the method is a handler for an event. It should return a Task . You can then exit the application in response to that task being completed:

private async Task GetEventData()
{ 
    //...
}

public Main()
{
  InitializeComponent();

  GetEventData()
      .ContinueWith(t => Environment.Exit(-1));
}

You can use the .Wait() method of Task to wait for it to complete.

public Main()
{
  InitializeComponent();

  GetEventData().Wait();

  // Exit the app
  Environment.Exit(-1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM