'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:

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?
Solution 1:[1]
Make the calling method async and await the result:
private async void Button_Click(object sender, RoutedEventArgs e)
{
var folderStructure = await restApiProvider.GetFolderStructure();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | McNets |
