2016-AspNet-MVC教学-8-异步Controller的应用

来源:互联网 发布:手机设计家具软件 编辑:程序博客网 时间:2024/05/17 18:13

步骤一 创建一个Asp.net MVC4 project Basic类型.

步骤二 创建一个Home控制器,代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcAsyncTest.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/        public ActionResult Index()        {            return View();        }          }}

步骤三 再创建一个MyAsync控制器,代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Threading.Tasks;using System.Threading;namespace MvcAsyncTest.Controllers{    public class MyAsyncController :AsyncController    {        //        // GET: /Async/        public Task<ViewResult> Index(string cs)        {            return Task.Factory.StartNew(() => RunThread(cs)).ContinueWith(t =>            {                ViewBag.str = t.Result;                return View();            });        }        private string RunThread(string input)        {            Thread.Sleep(5000);            return input+"5000";        }            }}

步骤四 为Home中的Index控制器,创建相应View:

@{    ViewBag.Title = "Index";}<h2>@Html.ActionLink("AsyncTest","Index","MyAsync",new{cs="abc"},null)</h2><h2>@Html.ActionLink("AsyncTest","Index","MyAsync",new{cs="efg"},null)</h2>

步骤五 为MyAsync控制器中的Index,创建相应View:

@{    ViewBag.Title = "Index";}<h2>@ViewBag.str</h2>

小结

这是MVC4最新的同步技术,里面采用了Lambda表达式,很简洁.异步操作主要用于I/O绑定操作(比如数据库访问和远程服务调用等),而非CPU绑定操作,因为异步操作对整体性能的提升来源于:当I/O设备在处理某个任务的时候,CPU可以释放出来处理另一个任务.如果耗时操作主要依赖于本机CPU的运算,采用异步方法反而会因为线程调度和线程上下文的切换而影响整体的性能。
0 0
原创粉丝点击