C#:在 C# 4.5 中等待请求完成
本文关键字:请求 等待 | 更新日期: 2023-09-27 18:36:45
我的 asp.net 4.0 应用程序中有一个 http 请求。我希望线程在继续之前等待。
HttpClient client = new HttpClient();
HttpResponseMessage responseMsg = client.GetAsync(requesturl).Result;
// I would like to wait till complete.
responseMsg.EnsureSuccessStatusCode();
Task<string> responseBody = responseMsg.Content.ReadAsStringAsync();
调用 。Wait() on the responseBody Task
在 4.5 中(你的标题是这样说的),你可以使用 async/await
public async void MyMethod()
{
HttpClient client = new HttpClient();
HttpResponseMessage responseMsg = await client.GetAsync("http://www.google.com");
//do your work
}
要下载字符串,您只需使用
public async void Question83()
{
HttpClient client = new HttpClient();
var responseStr = await client.GetStringAsync("http://www.google.com");
MessageBox.Show(responseStr);
}
一种选择是调用 。Wait(),但更好的选择是使用异步
public async void GetData()
{
using(HttpClient client = new HttpClient())
{
var responseMsg = await client.GetAsync(requesturl);
responseMsg.EnsureSuccessStatusCode();
string responseBody = await responseMsg.Content.ReadAsStringAsync();
}
}
}
这可以使用 async 关键字和 await 关键字来完成,如下所示:
// Since this method is an async method, it will return as
// soon as it hits an await statement.
public async void MyMethod()
{
// ... other code ...
HttpClient client = new HttpClient();
// Using the async keyword, anything within this method
// will wait until after client.GetAsync returns.
HttpResponseMessage responseMsg = await client.GetAsync(requesturl).Result;
responseMsg.EnsureSuccessStatusCode();
Task<string> responseBody = responseMsg.Content.ReadAsStringAsync();
// ... other code ...
}
请注意,await 关键字不会阻止线程。 相反,在异步方法的其余部分排队后,控制权将返回给调用方,以便它可以继续处理。 如果您需要MyMethod()
的调用方也等到客户端。GetAsync() 完成,那么你最好使用同步调用。