簡體   English   中英

如何從異步中返回一個字符串

[英]How to return a string from async

我的方法是調用Web服務並異步工作。

得到回應時,一切正常,我得到了回應。

當我需要返回此響應時,問題就開始了。

這是我的方法的代碼:

 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

如何獲取結果字符串,就像我在方法中使用數據一樣。

您需要執行此操作,因為您同步調用async方法:

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

Task<string>返回類型視為將來返回值的“promise”。

如果您異步調用異步方法,那么它將如下所示:

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

異步方法返回表示未來值任務 為了獲得包含在該任務中的實際值,您應該await它:

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

請注意,這將要求您的調用方法是異步的。 這既自然又正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM