首先来一个小的asp.net mvc 4的sample,代码以下:web
HomeController:ajax
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.SessionState; namespace MvcApplication2.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult Test() { //这里为了测试执行了等待30秒的代码,实际项目中会遇到 //不少相似须要很长时间的状况,好比调用webservice,或者处理很大数据 System.Threading.Thread.Sleep(30000); return View(); } } }
Global.asax:浏览器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MvcApplication2 { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Session_Start(object sender, EventArgs e) { } } }
Views中的代码省略。session
这么简单的程序若是咱们运行会发现一个问题:当我打开浏览器打开两个tab,先在一个tab中打开/Home/Test,这时这个tab会等30秒才能呈现页面,在这期间我在另外一个tab中打开 /Home/Index,只有等第一个tab30秒事后,第二个tab才能呈现/Home/Index。而这种状况若是在实际项目中会很是影响性能,好比咱们若是须要访问webservice耗用大量时间获取一些数据,同时咱们又要经过ajax发送请求去处理一个查询,这时若是按照上面的作法,只能等待webservice方法执行完毕后才能处理ajax请求。(Note:这种状况只有在同一个session下存在,若是上面的操做不打开两个tab而是换成两个浏览器,相似状况不会发生)mvc
解决方案:app
这里咱们须要了解一下asp.net mvc 中的SessionState的做用:asp.net
在stackoverflow的一片文章记录到:less
Session state is designed so that only one request from a particular user/session occurs at a time. So if you have a page that has multiple AJAX callbacks happening at once they will be processed in serial fashion on the server. Going session-less means that they would execute in parallel.性能
大意就是Session state是用来将同一个session的请求按顺序处理,若是须要并行处理则须要设置session-less。测试
如何设置SessionState呢?
mvc4中能够在controller上面加以下Attribute:(在System.Web.SessionState命名空间下)
[SessionState(SessionStateBehavior.ReadOnly)]
mvc3加以下Attribute:
[ControllerSessionState(SessionStateBehavior.ReadOnly)]
SessionStateBehavior四个选项中的区别: