ASP.NET MVC Lock锁的测试

思路:我们让后台Thread.Sleep一段时间,来模拟一个耗时操作,而这个时间可以由前台提供。

我们开启两个或以上的页面,第一个耗时5秒(提交5000),第二个耗时1秒(提交1000)。

期望的测试结果:

不加Lock锁,第二个页面会先执行完,因为耗时短(1秒)。

加了Lock锁,第二个页面会一直等待,直到第一个页面执行完成后再进行。

后台:

cs 复制代码
    public class DBController : Controller
    {
        /// <summary>
        /// 显示页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Concurrency()
        {
            return View();
        }

        /// <summary>
        /// 模拟耗时操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ConcurrencySubmit(string msec)
        {
            if (!string.IsNullOrEmpty(msec))
            {
                 System.Threading.Thread.Sleep(int.Parse(msec));
                 LogHelper.Info("submit:" + msec);
            }

            return View("Concurrency");
        }
    }

前台页面 Concurrency.cshtml:

html 复制代码
@using(Html.BeginForm("ConcurrencySubmit", "DB", FormMethod.Post))
{
@Html.TextBox("msec",1000)
<button>提交</button>
}

然后开两个页面,第一个5秒,第二个1秒,同时提交。

发现第二个页面先执行完毕了,因为耗时最短。

接下来我们使用Lock来进行防并发处理,修改后台代码:

cs 复制代码
    public class DBController : Controller
    {
        private static object locker = new object();
        
        /// <summary>
        /// 显示页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Concurrency()
        {
            return View();
        }
        
        /// <summary>
        /// 模拟耗时操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ConcurrencySubmit(string msec)
        {
            lock (locker)
            {
                if (!string.IsNullOrEmpty(msec))
                {
                    System.Threading.Thread.Sleep(int.Parse(msec));
                    LogHelper.Info("submit:" + msec);
                }
            }

            return View("Concurrency");
        }
    }

同样的方法,再次提交。这次会发现第二个页面会等待,直到第一个页面执行完成后才执行

相关推荐
张宇Joaquin1 天前
高性能计算之MPI——集合通信漫谈
服务器·microsoft·asp.net
kybs19915 天前
springboot网上购书商城---附源码15749
java·javascript·spring boot·python·c#·asp.net·php
四代水门6 天前
三、计算机网络
服务器·计算机网络·asp.net
玖石书10 天前
ASP.NET Core迁移Spring对照系列:文件系统操作篇
spring·asp.net
仙人球部落 揞殺11 天前
细说ASP.NET的各种异步操作
后端·asp.net
全麦面包 time展天12 天前
瀚海拾贝(一)HTTP协议/IIS 原理及ASP.NET运行机制浅析【图解】
网络协议·http·asp.net
吴懿不在 不负信仰12 天前
用三张图片详解Asp.Net 全生命周期
后端·asp.net
情可轻 秦任之13 天前
ASP.NET页面优化,性能提升8倍的方法
后端·asp.net
深爱水瓶 血影S狂风13 天前
Asp.Net无刷新上传并裁剪头像
后端·asp.net
玖石书14 天前
ASP.NET Core迁移Spring系列:运行时与 GC 篇
后端·spring·asp.net