本文介绍了有什么不对的异步任务的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是一个简单的异步任务,但我一直有奇怪的编译器错误。这code从一个ASP.NET 4项目中的Web API服务,与VS2010创建的。

Code:

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();
                });
            });
        }
}
解决方案

The 364 error is perfectly normal because you are returning a Task<Task<HttpResponseMessage>> instead of Task<HttpResponseMessage>. Once you fix that the 361 error will also disappear.

So you could Unwrap the result:

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

这篇关于有什么不对的异步任务的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 23:04