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