Search code examples
c#asynchronousasync-awaitxamarin.formsportable-class-library

Calling async function in sync method in PCL in Xamarin Forms


I have this function:

public async Task<string> GetData() 
{
    var httpClient = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "My Link Here...");
    var response = await httpClient.SendAsync(request);
    string value = await response.Content.ReadAsStringAsync ();
    return value;
}

It gets the data from a webapi, and then I have to use that data to build a chart in Xamarin Forms using Steema Teechart. The problem is that I can't call the function GetData() in the class where I build the chart, because the method in which I want to use the data isn't async. How Am I supposed to call GetData() and use the string?

I have tried:

Task<string> s = GetData ();
s.Wait ();
string initialValues = s.Result;

But it stops my app and crashes it after a while.


Solution

  • The problem is that I can't call the function GetData() in the class where I build the chart, because the method in which I want to use the data isn't async. How Am I supposed to call GetData() and use the string?

    You make the calling method async and then use await:

    string initialValues = await GetData();
    

    Yes, this means that your calling method also needs to return a Task/Task<T>, which means that its calling methods should also be async, etc. This "growth" of async is perfectly natural.