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

前端 未结 4 988
故里飘歌
故里飘歌 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:59

    As someone exploring how to get all of this working in .NET 4.0 as well, I haven't found the given answers on this thread and others complete enough to immediately get up and running. So the following is a more comprehensive answer of what to simply do:

    ======= STEP #1) INSTALL Microsoft ASP.NET Web API Client Libraries (RC) 4.0.20505.0 =======

    http://nuget.org/packages/Microsoft.AspNet.WebApi.Client

    PM> Install-Package Microsoft.AspNet.WebApi.Client
    

    INSTALLS: System.Net.Http.dll, System.Net.Http.Formatting.dll, System.Net.Http.WebRequest.dll, Newtonsoft.Json.dll

    ======= STEP #2) Microsoft .NET Framework 4 HTTP Client Libraries 2.0.20505.0 =======

    http://nuget.org/packages/Microsoft.Net.Http.

    PM> Install-Package Microsoft.Net.Http.
    

    If you followed step #1 already, NuGet should have actually already grabbed this dependency: System.Net.Http.dll. System.Net.Http. is what provides HttpClient, HttpRequestMessage and HttpResponseMessage.

    At this point, you will be getting errors when using async/await (though these keywords still show up as keywords) saying things like:

    Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

    Thus:

    ======= STEP #3) Async Targeting Pack for Visual Studio =======

    http://www.microsoft.com/en-us/download/details.aspx?id=29576

    PM> Install-Package Microsoft.CompilerServices.AsyncTargetingPack
    

    ('...Visual Studio 11' name needs updated on NuGet, both are version 1.0.0)

    Installs 1 dll: Microsoft.CompilerServices.AsyncTargetingPack.Net4.dll

    "The "Async Targeting Pack for Visual Studio 2012" enables projects targeting .NET Framework 4.0 or Silverlight 5 to use the Async language feature in C# 5 ... " http://www.microsoft.com/en-us/download/details.aspx?id=29576

    Among other things, adds TaskEx (a .NET 4.0 version that fills in many new Task features. TaskEx is only for the 4.0 version... so .NET 4.5: "Task.Run" is in 4.0: "TaskEx.Run", many other things are like this with this library)

    Suddenly, await and async and the whole works starts working like a charm! If you reflect in, one of the most important things about this is the class (declared without a namespace): AsyncCompatLibExtensions. A static class containing extension methods onto especially: 1) Stream. E.g. ReadAsync. So now stream.ReadAsync suddenly appears! (it actually cleanly wraps stream's BeginRead/BeginWrite, if you want to know), 2) WebClient. E.g. webClient.DownloadStringTaskAsync, and more.

提交回复
热议问题