[英]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.