這可以通過使用async keyword和await 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()完成,那麼最好使用同步調用。
您是否嘗試使用同步方法(而不是異步)? – funerr
它是.NET 4.5(http://msdn.microsoft.com/de-de/library/system.net.http.httpcontent.readasstringasync(v=vs.110).aspx)。羅伯特的回答是正確的。 – Sascha
我不太明白你的問題,但是如果你調用.result,它應該阻止線程,直到它完成對嗎? – Vincent