6

我的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();
4

4 回答 4

8

在 responseBody 任务上调用 .Wait()

于 2012-06-11T17:13:02.660 回答
3

在 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);

}
于 2012-06-11T17:21:20.927 回答
2

一种选择是调用 .Wait() 但更好的选择是使用 async

public async void GetData()
{
    using(HttpClient client = new HttpClient())
    {
        var responseMsg = await client.GetAsync(requesturl);
        responseMsg.EnsureSuccessStatusCode();
        string responseBody = await responseMsg.Content.ReadAsStringAsync();
    }
}

}

于 2012-06-11T17:25:20.423 回答
1

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

于 2012-06-11T17:33:02.633 回答