在 Xamarin Forms 的 PCL 同步方法中调用异步函数

Calling async function in sync method in PCL in Xamarin Forms

我有这个功能:

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;
}

它从 webapi 获取数据,然后我必须使用该数据使用 Steema Teechart 在 Xamarin Forms 中构建图表。问题是我无法在构建图表的 class 中调用函数 GetData(),因为我想要使用数据的方法不是异步的。我应该如何调用 GetData() 并使用字符串?

我试过:

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

但它会停止我的应用程序并在一段时间后崩溃。

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?

你制作调用方法async然后使用await:

string initialValues = await GetData();

是的,这意味着你的调用方法还需要return一个Task/Task<T>,也就是说个调用方法也应该是async,等等。这个async的"growth"很自然。