Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

Make the calling method async and await the result:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading