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

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

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

Even ContinueWith (non-generic) returns Task implicitly but this error still exists.

代码:

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

最佳答案

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

关于c# - 这个异步任务方法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9799771/

相关文章:

C# - 使用 foreach 遍历方法参数

asp.net-web-api - Asp.Net Web API : Protecting with a token?

c# - 使用 Task.Run 的后台线程

parallel-processing - 工作窃取和双端队列

c# - Metro C# 中的虚拟异步方法

c# - KeyEventArgs.KeyData、KeyEventArgs.KeyCode 和 KeyEventArgs.KeyValue

c# - 用于 64 位操作系统的 itextsharp

c# - 部分声明不能指定不同的基类?

c# - 如何为异步 Web API 编写单元测试

asp.net-mvc - ASP.NET 5 中的 Web 应用程序