webworm
webworm

Reputation: 11019

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

Upvotes: 0

Views: 2456

Answers (2)

Servy
Servy

Reputation: 203827

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));
}

Upvotes: 1

nvoigt
nvoigt

Reputation: 77324

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);
}

Upvotes: 0

Related Questions