5
這只是一個簡單的異步任務,但我一直有奇怪的編譯錯誤。此代碼來自ASP.NET 4項目中的Web API服務,使用VS2010創建。這個異步任務方法有什麼問題?
即使ContinueWith(非泛型)隱式返回任務,但此錯誤仍然存在。
代碼:
public class TestController : ApiController
{
public Task<HttpResponseMessage> Test()
{
string url = "http://www.stackoverflow.com";
var client = new HttpClient();
return client.GetAsync(url).ContinueWith<HttpResponseMessage>((request) =>
{
// Error 361 'System.Threading.Tasks.Task' does not contain a definition
// for 'Result' and no extension method 'Result' accepting a first argument
// of type 'System.Threading.Tasks.Task' could be found
// (are you missing a using directive or an assembly reference?)
var response = request.Result;
response.EnsureSuccessStatusCode();
// Error 364 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>' to 'System.Net.Http.HttpResponseMessage'
return response.Content.ReadAsStringAsync().ContinueWith<HttpResponseMessage>((read) =>
{
return new HttpResponseMessage();
});
});
}
}
謝謝,我非常忘了返回值被包裹在一個任務<>每個ContinueWidth。你的代碼已經編譯好了,但是我不確定它是否仍然能夠正常工作:在執行client.GetAsync和response.Content.ReadAsStringAsync調用期間,線程將被釋放一段時間。 – 2012-03-21 09:15:22
@Tiendq,我用一個更好的例子使用'Unwrap'更新了我的答案。這將確保在執行HTTP請求期間工作線程將是空閒的。 – 2012-03-21 09:59:43