Home > OS >  How to use async calls in WPF event handlers
How to use async calls in WPF event handlers

Time:05-07

I have this event handler in WPF with async call.

private void Button_Click(object sender, RoutedEventArgs e)
{
    var folderStructure = restApiProvider.GetFolderStructure();
}

Here is the implementation of GetFolderStructure():

public async Task<IList<string>> GetFolderStructure()
{
    var request = new RestRequest(string.Empty, Method.Get);
    var cancellationTokenSource = new CancellationTokenSource();
    var response = await client.GetAsync(request, cancellationTokenSource.Token);

    return JsonConvert.DeserializeObject<IList<string>>(response.Content);
}

I need to get the data from GetFolderStructure() in order to continue in the app but this is the output I get: enter image description here

If I add folderStructure.Wait(); the call doesn't complete itself and the whole app get stuck. However if I change var folderStructure = restApiProvider.GetFolderStructure(); to restApiProvider.GetFolderStructure(); the call is completed immediately and stuck doesn't occure.

What am I missing?

CodePudding user response:

Make the calling method async and await the result:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var folderStructure = await restApiProvider.GetFolderStructure();
}
  • Related