2015-07-21 20 views
6

我的方法正在调用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

我怎么能得到结果字符串,因为我在我的方法中使用了数据

+1

您需要访问Task的'Result'属性才能获得所需的输出。 –

回答

8

你需要这样做,因为你所呼叫的async方法同步:在Task<string>返回类型的

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

觉得作为一个“承诺”在未来返回一个值。

如果您呼叫的异步方法异步那么这将是这样的:

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

我称之为异步,它的工作原理,谢谢。我会尽快接受。 – eeadev

+1

等待是没有必要的。 Result属性阻塞调用线程直到任务完成。请参阅https://msdn.microsoft.com/en-us/library/dd537613(v=vs.110).aspx – Emile

+0

@Emile你是对的!我更新了答案。 –

5

异步方法返回一个任务,代表未来价值。为了得到包裹在该任务的实际值,你应该await它:

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

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