一个简图来描述下Aspnet MVC下的异步调用

  { request }
/ \/
-------ISS------- > work thread
| \
| \ route - aysn controller
| \
| \ [invoke] clr thread pool
| /
| /
| / complete -> asyncManager
| /
|------asyncManager

从简图可以了解:
用户发送请求,服务器路由到控制器,控制器到action,action内部通过线程池调用新线程执行request,然后将数据返回给用户。

该简图涉及到controller的一个属性AsyncManager
asyncManagerde的作用主要体现在两点:
1. 标识异步的开始和结束,通 过  AsyncManager.OutstandingOperations.Increment/OutstandingOperations.Decrement
2. 在执行线程到结束回调过程中的参数传递 通过AsyncManager.Parameters (类型为字典,传递参数时候需要注意Key需要跟结果参数回调的参数名一致)。

asyncManager在异步调用中并不是必须的。

异步虽好,但并不是所有的场合都是适合的,一般来说如果没有长耗时和分布的需求情况下,异步是没要的

在aspnet mvc中实现异步操作有三种方式:

1.通过异步控制器AsyncController
  自定义控制器通过继承AsyncController,在内部定义XXXAsync/XXXCompleted格式的action,例如:

public void IndexAsync() { }
public ActionResult IndexCompleted(string parameter); //其中indexCompleted中的参数parameter
//通过AsyncManager.Parameters ["parameter'] = XX传递
//参数名和KEY要保持一致性

Async和completed定义总是成对出现了,async定义的方法用于执行异步操作,而completed定义的方法用于返回结果.

通过XXasync和XXcompeleted定义的方法,ASPNET MVC在调用时候并不是以异步的方式调用,所以真正的工作还是需要我们自己async中定义异步操作.一个简单的例子:

    public class CustomAsyncController: AsyncController
{
public void IndexAsync() {
//increment不写参数情况默认计数为1
//如果存在多个task需要添加相应的计数值,以保证结果能正确的返回
AsyncManager.OutstandingOperations.Increment();
Task.Factory.StartNew(() =>
{
int sum = ;
for (int i = ; i < ; i++) { sum += i; } //传递参数给XXXCompleted
AsyncManager.Parameters["sum"] = sum; //end
AsyncManager.OutstandingOperations.Decrement();//多个任务要多次调用,调用次数一般等于increment中设置的计数
}); }
public ActionResult IndexCompleted(string sum)
{
return Content(sum.ToString());
}
}

2.通过async和await关键字

async/await关键字用于标识异步操作,我们用一个简单的例子来演示async/await的使用

a.例子我们先定义个webapi,用于返回用户信息

b.通过服务类,异步调用改用webapi接口返回用户信息

c.控制器调用服务类返回数据结果

    public class UserController : ApiController
{
private static UserRepository _respository = new UserRepository(); [System.Web.Http.HttpGet]
public IList<UserModel> GetAll()
{
return _respository.GetAll();
}
}
   public class UserService
{
private static UserService instance = null;
public static UserService Instance
{
get
{
if (instance == null)
instance = new UserService(); return instance;
}
}
public async Task<IList<UserModel>> GetUsersAsync( CancellationToken token =default(CancellationToken))
{
var uri = "http://localhost:3541/api/user/getall";
using(HttpClient client = new HttpClient())
{
var response = await client.GetAsync(uri);
return await response.Content.ReadAsAsync<IList<UserModel>>();
}
}
}
    public class CustomController : Controller
{
public async Task<ActionResult> Index()
{
IList < UserModel > models = await UserService.Instance.GetUsersAsync(); return Json(models,JsonRequestBehavior.AllowGet);
}
}

3.直接通过返回task实现异步

  最简单最直接的一种方式了

    public class HomeController : AsyncController
{
public Task<ActionResult> Index()
{
return Task.Factory.StartNew(() =>
{
return new List<UserModel>
{
new UserModel {Name ="visonme" },
new UserModel {Name = "visonme2" }
};
}).ContinueWith<ActionResult>((task) =>
{
return Json(task.Result, JsonRequestBehavior.AllowGet);
});
}
}

Aspnet MVC 异步调用的更多相关文章

  1. [MVC] - 异步调用后台的常用方法。

    1. 直接调用Action @Html.Action("GetTopArticle", "Home") 2. 通过url, 并用Jquery异步加载. < ...

  2. MVC 异步调用

    @{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport&q ...

  3. Spring MVC 异步处理请求,提高程序性能

    原文:http://blog.csdn.net/he90227/article/details/52262163 什么是异步模式 如何在Spring MVC中使用异步提高性能? 一个普通 Servle ...

  4. mvc路由引起异步调用web服务的问题

    从一篇blog得知使用脚本可以异步调用Web服务,觉得很新鲜,因为自己很少用到Web服务,所以决定写一写看看什么效果. 首先在UI项目(我使用的是MVC4.0)里创建一个Web服务. 添加Web服务后 ...

  5. 【ASP.Net MVC】AspNet Mvc一些总结

    AspNet Mvc一些总结 RestaurantReview.cs using System; using System.Collections.Generic; using System.Comp ...

  6. AspNet MVC中各种上下文理解

    0  前言 AspNet MVC中比较重要的上下文,有如下: 核心的上下文有HttpContext(请求上下文),ControllerContext(控制器上下文) 过滤器有关有五个的上下文Actio ...

  7. ASPNET MVC中断请求

    ASPNET MVC如何正确的中断请求? 感觉是这样? 在aspnet开发过程中如果想要中断当前的http处理,以前在aspnet中一直是Response.End(); 在这Response.End( ...

  8. AspNet MVC : 操作/控制器过滤器(action filter)

    1.Action Filter Action Filter提供了在执行action/controller前后对请求/响应修改的能力,可以应用于action和控制器上,作用在控制器上将自动被应用到该控制 ...

  9. c#异步编程(三)—ASP.NET MVC 异步控制器及EF异步操作

    ASP.NET MVC 异步控制器及EF异步操作 异步控制器 ASP.NET MVC2后开始了对异步请求管道的支持,异步请求管道的作用是允许web服务器处理长时间运行的请求,比如 那些花费大量时间等待 ...

随机推荐

  1. 排序之直接插入排序(Straight Insertion Sort)

    一.直接插入排序(Straight Insertion Sort) 排序的过程如下:给定无需序列:(3,6,9,7,1,8,2,4) ① 3,6,9,7,1,8,2,4 (将6插入到有序序列3中) ② ...

  2. MySQL Server类型之MySQL客户端工具的下载、安装和使用

    本博文的主要内容有 .MySQL Server 5.5系列的下载 .MySQL Server 5.5系列的安装 .MySQL Server 5.5系列的使用 .MySQL Server 5.5系列的卸 ...

  3. sonarQube本机扫描C#项目

    因项目需要,需要使用sonarQube对代码进行扫描并查看,因对sonarQube不熟悉,所以先在本机进行查看. 参考了张老师的博客:http://www.cnblogs.com/danzhang/p ...

  4. Epoll之ET、LT模式

    Epoll之ET.LT模式 在使用epoll时,在函数 epoll_ctl中如果不设定,epoll_event 的event默认为LT(水平触发)模式. 使用LT模式意味着只要fd处于可读或者可写状态 ...

  5. SecondarySort 原理

    定义IntPair 以及 IntPair(first,second)的compareto,先比較first的大小,再比較second的大小 定义FirstPartitioner是为了让partitio ...

  6. delphi TColorDialog

    TColorDialog 预览          实现过程 动态创建和使用颜色对话框 function ShowColorDlg:TColor;begin  with TColorDialog.Cre ...

  7. MVC ASPX(webForm)视图引擎 &lt;%:%&gt; 与&lt;%=%&gt;的差别

    控制器 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syste ...

  8. Androidannotation使用之@Rest与server交互的JSON数据转换(二)

    开篇 之前的一篇博客:Androidannotation使用之@Rest获取资源及用户登录验证(一):http://blog.csdn.net/nupt123456789/article/detail ...

  9. Objective-c Category使用

    Objective-c  Category使用 转载:http://blog.csdn.net/lovefqing/article/details/8289851 什么是Category Catego ...

  10. Struts2 ValueStack

    一.作用 可以作为一个数据中转站,用在前台和后台数据传递 二.生命周期 ValueStack的生命周期是随着request的创建而创建,随request的销毁而销毁. 三.结构 OgnlValueSt ...