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");
        }
    }

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

相关推荐
滴滴答答哒2 天前
ASP.NET Core + FaceRecognitionDotNet 人脸识别实战:DI 单例、特征向量持久化与 1:N 比对
后端·asp.net
咖丨喱4 天前
【P2P 邀请后 5G 单信道扫描 dwell 加长】
服务器·5g·asp.net
鸠摩智首席音效师12 天前
如何清理 ASP.NET 临时文件 ?
后端·asp.net
小羊没烦恼!18 天前
如何在IIS6,7中部署ASP.NET网站?
数据库·后端·python·web安全·asp.net
宝桥南山19 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
Lost of 程序猿19 天前
责任链模式实战:审批流里“层层把关“的艺术
后端·设计模式·asp.net·责任链模式
刚子编程24 天前
我用 ASP.NET Core 做了个水稻病虫害检查系统
后端·asp.net