Kotkoroid
Kotkoroid

Reputation: 432

How to use async calls in WPF event handlers

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?

Upvotes: 2

Views: 1225

Answers (1)

McNets
McNets

Reputation: 10807

Make the calling method async and await the result:

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

Upvotes: 4

Related Questions