这个异步任务方法有什么问题?

时间:2012-03-21 06:43:34

标签: c# asp.net-web-api task-parallel-library async-await

这只是一个简单的异步任务,但我总是遇到奇怪的编译器错误。此代码来自ASP.NET 4项目中的Web API服务,使用VS2010创建。

  

Even ContinueWith(非泛型)隐式返回Task,但此错误仍然存​​在。

代码:

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

1 个答案:

答案 0 :(得分:5)

364错误完全正常,因为您要返回Task<Task<HttpResponseMessage>>而不是Task<HttpResponseMessage>。一旦你修复了361错误也会消失。

所以你可以Unwrap结果:

public Task<HttpResponseMessage> Test()
{
    string url = "http://www.stackoverflow.com";
    var client = new HttpClient();
    return client.GetAsync(url).ContinueWith(request =>
    {
        var response = request.Result;
        response.EnsureSuccessStatusCode();
        return response.Content.ReadAsStringAsync().ContinueWith(t =>
        {
            var result = new HttpResponseMessage();
            response.CreateContent(t.Result);
            return response;
        });
    }).Unwrap();
}