【问题标题】:How to return a string from async如何从异步返回字符串
【发布时间】:2017-02-01 00:05:29
【问题描述】:

我的方法是调用网络服务并异步工作。

收到回复后,一切正常,我正在收到回复。

当我需要返回此响应时,问题就开始了。

这是我的方法的代码:

 public async Task<string> sendWithHttpClient(string requestUrl, string json)
        {
            try
            {
                Uri requestUri = new Uri(requestUrl);
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Clear();
                    ...//adding things to header and creating requestcontent
                    var response = await client.PostAsync(requestUri, requestContent);

                    if (response.IsSuccessStatusCode)
                    {

                        Debug.WriteLine("Success");
                        HttpContent stream = response.Content;
                        //Task<string> data = stream.ReadAsStringAsync();    
                        var data = await stream.ReadAsStringAsync();
                        Debug.WriteLine("data len: " + data.Length);
                        Debug.WriteLine("data: " + data);
                        return data;                       
                    }
                    else
                    {
                        Debug.WriteLine("Unsuccessful!");
                        Debug.WriteLine("response.StatusCode: " + response.StatusCode);
                        Debug.WriteLine("response.ReasonPhrase: " + response.ReasonPhrase);
                        HttpContent stream = response.Content;    
                        var data = await stream.ReadAsStringAsync();
                        return data;
                     }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ex: " + ex.Message);
                return null;
            }

我这样称呼它:

      Task <string> result =  wsUtils.sendWithHttpClient(fullReq, "");           
      Debug.WriteLine("result:: " + result); 

但在打印结果时,我看到如下内容:System.Threading.Tasks.Task

如何像在方法中使用 data 一样获取结果字符串。

【问题讨论】:

  • 您需要访问TaskResult 属性以获得所需的输出。

标签: c# asynchronous async-await


【解决方案1】:

您需要这样做,因为您正在同步调用async 方法

  Task<string> result =  wsUtils.sendWithHttpClient(fullReq, "");           
  Debug.WriteLine("result:: " + result.Result); // Call the Result

Task&lt;string&gt; 返回类型视为“承诺”在未来返回一个值。

如果您异步调用 async 方法,则如下所示:

  string result =  await wsUtils.sendWithHttpClient(fullReq, "");           
  Debug.WriteLine("result:: " + result);

【讨论】:

【解决方案2】:

异步方法返回一个任务,代表一个未来值。为了获得包含在该任务中的实际值,您应该 await 它:

string result = await wsUtils.sendWithHttpClient(fullReq, "");
Debug.WriteLine("result:: " + result);

请注意,这将要求您的调用方法是异步的。这既自然又正确。

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多