这可以使用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()
也等到 client.GetAsync() 完成,那么您最好使用同步调用。