zoukankan      html  css  js  c++  java
  • Session阻塞 读写锁引发的小问题

    •   引子

        我们来看两个ajax方法,先后的问题,会有什么样的结果?

       Javascript:

      $(function () {
                //第一个
                $.ajax({
                    type: "POST",
                    url: "/Home/Method1",
                    success: function (msg) {
                        $('#m1').html('第一个方法完成');
                    }
                });
                //第二个
                $.ajax({
                    type: "POST",
                    url: "/Home/Method2",
                    success: function (msg) {
                        $('#m2').html('第二个方法完成');
                    }
                });
            });

      服务端

      public class HomeController : Controller
        {
            //
            // GET: /Home/
    
            public ActionResult Index()
            {
                Session["test"] = 123;
                return View();
            }
    
            public ActionResult Method1()
            {
                Thread.Sleep(6000);
                return Json("");
            }
    
            public ActionResult Method2()
            {
                return Json("");
            }
    
        }

           本以为:两个ajax是异步请求,谁先处理完,就谁先返回回来。

          可是现实却大大出乎我的意料。见下图。

    明显第二个请求是等第一个请求处理完了,才执行的。

    • 根源

    其实问题是出现在Session上,那么我们把Session["test"]  去掉,这样再看结果:

    原来妖孽就是Session,同一会话,即请求的SessionId是相同的,都会初始化Session对象,并锁住Session对象;其他同一会话的请求要用到Session对象,只能等待。因此才会出现前面的情况。

    • 解决

    只需要标识当前会话session行为为只读行为,就不会加锁   

           [SessionState(SessionStateBehavior.ReadOnly)]

     

     

    [SessionState(SessionStateBehavior.ReadOnly)]
        public class HomeController : Controller
        {
            //
            // GET: /Home/
    
            public ActionResult Index()
            {
                Session["test"] = 123;
                return View();
            }
    
            public ActionResult Method1()
            {
                Thread.Sleep(6000);
                return Json("");
            }
    
            public ActionResult Method2()
            {
                return Json("");
            }
        }

     

     

     结果符合表述,如下图:

  • 相关阅读:
    LinkedBlockingQueue 单向链表实现的阻塞队列
    ArrayBlockingQueue 实现定时推送数据
    前台接收后端的JsonArray,循环输入页面表格
    一个常用的文件操作类
    DelayQueue 延时获取元素的无界阻塞队列
    单例设计模式
    使用SQL Server Data Tools (SSDT)比较和同步两个数据库的架构或者数据
    Entity Framework技能知识点测试2
    JS设置localStorage有效期
    Entity Framework技能知识点
  • 原文地址:https://www.cnblogs.com/cainiaoguoshi/p/3976100.html
Copyright © 2011-2022 走看看