我的方法是调用网络服务并异步工作。
收到回复时,一切正常,我正在收到回复。
当我需要返回此响应时,问题就开始了。
这是我的方法的代码:
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);
关于c# - 如何从异步返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536082/