2012-06-11 80 views
4

我在我的asp.net 4.0应用程序中有一个http请求。我希望线程在继续之前等待。C#:等待一个请求在C#4.5中完成

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(); 
+1

您是否尝试使用同步方法(而不是异步)? – funerr

+0

它是.NET 4.5(http://msdn.microsoft.com/de-de/library/system.net.http.httpcontent.readasstringasync(v=vs.110).aspx)。罗伯特的回答是正确的。 – Sascha

+0

我不太明白你的问题,但是如果你调用.result,它应该阻止线程,直到它完成对吗? – Vincent

回答

8

在呼叫.Wait()的responseBody任务

+0

我试过了,它不起作用。 responseBody.Wait(); – user516883

+0

它是做什么的? –

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

} 
2

一个选项是调用.Wait(),但更好的选择是使用异步

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

}

1

这可以通过使用async keywordawait keyword来完成,像这样:

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

+0

您也可以使用await检索responseBody作为字符串。你也应该用一个使用块来处理客户端 –

+0

非常好的一点。我想这就是我发布不完整的代码而没有添加任何东西来显示。 –