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

标签 c# asynchronous async-await xamarin.forms portable-class-library

我有这个功能:

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/

相关文章:

C# 异步,没有任务等待

c# - 检查 ICollection 是否实际上是只读的正确方法

c# - 初始化 Blazor 组件中的对象

c# - 如果我为操作系统版本不支持的 API 使用 DllImport (C# .NET),会发生什么情况

Javascript forEach 吞咽异常

java - 在异步方法中调用 Thread.sleep()

java - 处理异步响应

c# - 代码可重用性 : how to refactor checks to be more readable and reusable, 职责分离?

Firebase 查询收集和合并子集合数据

javascript - 使用嵌套的 Promise 创建 Promise 队列