How do I convert .net 4.5 Async/Await example back to 4.0

前端 未结 4 991
故里飘歌
故里飘歌 2021-02-07 12:36

What would the equivalent asp.net mvc 4.0 code look like?

using System.Net;
using System.Net.Http;
using System.Web.Mvc;
using System.Threading.Tasks;
using Newt         


        
4条回答
  •  星月不相逢
    2021-02-07 12:53

    WARNING There is no error checking!

    Well I feel like I learned something today, have a read of this article http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx to learn a better way to handle this :)

    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    using Newtonsoft.Json;
    namespace DribbbleR.Web.Controllers
    {
        public class HomeController : Controller
        {
            private static dynamic shots;
            private HttpClient client = new HttpClient();
            private string url = "http://api.dribbble.com/shots/everyone?per_page=30";
    
            public Task Index()
            {    if (shots == null)
                 shots = Task.Factory.StartNew
                       (() => return DownloadContent();).Unwrap();    
                 return shots;
            }
            public Task DownloadContent()
            {    var responseTask = client.GetAsync(url);
                 var readTask = responseTask.ContinueWith
                     (t =>
                         {   t.Result.EnsureSuccessStatusCode();
                             return t.Result.Content.ReadAsStringAsync();
                          }
                      ).Unwrap();
                var deserializeTask = readTask.ContinueWith
                      (t => return JsonConvert.DeserializeObjectAsync(t.Result);)
                .Unwrap();
                var viewTask = deserializeTask.ContinueWith
                      (t =>  return this.View(t.Result););
                return viewTask;
            }
        }
    }
    

提交回复
热议问题