我正在使用C#和.NET Framework 4.0开发一个库。
我有这种方法在ASP.NET Web Api 2 Web服务上输入一些东西。
public async Task<string> PrepareAndStartv2(
string orderNumber,
string userName,
string systemName)
{
string uri =
string.Format(PrepareAndStartUri, orderNumber, userName, systemName);
string batchName = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(webApiHost);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
Task<HttpResponseMessage> response = client.PutAsync(uri, content);
HttpResponseMessage message = response.Result;
Task<string> task = message.Content.ReadAsStringAsync();
batchName = await task;
}
return batchName;
}
我添加了message.Content.ReadAsStringAsync()
来获取方法返回的字符串。在那之后,我被迫和Task<string>
,await
和async
无处不在。
是否还有其他选项可以在HttpContent
中使用await
,Task<string>
和async
读取字符串?
也许在这个PrepareAndStartv2
方法中运行一个等待我将正在使用ReadAsStringAsync()
读取字符串的任务。
答案 0 :(得分:2)
调用异步方法后可以使用Task.Result以避免强制异步执行自己的方法:
public string PrepareAndStartv2(
string orderNumber,
string userName,
string systemName)
{
string uri =
string.Format(PrepareAndStartUri, orderNumber, userName, systemName);
string batchName = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(webApiHost);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
HttpResponseMessage message = client.PutAsync(uri, content).Result;
batchName = message.Content.ReadAsStringAsync().Result;
}
return batchName;
}