我有这个功能:
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 中构建图表。问题是我无法在构建图表的类中调用函数 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();
是的,这意味着您的调用方法还需要返回 Task
/Task<T>
,这意味着其调用方法也应该是 async
等等async
的这个“成长”非常自然。
关于c# - 在 Xamarin Forms 中的 PCL 同步方法中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834530/