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

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

相关推荐
William_cl21 小时前
ASP.NET Core 视图组件:从入门到避坑,UI 复用的终极方案
后端·ui·asp.net
William_cl1 天前
ASP.NET Core ViewData:弱类型数据交互的精髓与避坑指南
后端·asp.net·交互
Net蚂蚁代码2 天前
【如何在ASP.Net Core中使用 IHostedService的方法】执行自动服务运行
后端·asp.net
Caco.D2 天前
Aneiang.Pa.News:属于你自己的全平台热点聚合阅读器
爬虫·asp.net·aneiang.pa·热榜新闻
咖丨喱3 天前
【解析并缓存 P2P_ATTR_DEVICE_INFO】
缓存·asp.net·p2p
咖丨喱4 天前
【解决Miracast出现组形成失败问题】
后端·asp.net
智商偏低4 天前
ABP 框架中的 HttpContextWebClientInfoProvider
后端·asp.net
William_cl7 天前
ASP.NET入门必吃透:HTTP 协议从流程到状态码,代码 + 避坑指南
后端·http·asp.net
William_cl7 天前
ASP.NET View 层核心:布局页_Layout.cshtml 与 @RenderBody () 通关指南
后端·asp.net
William_cl7 天前
【C# ASP.NET】局部视图 @Html.Partial 全解析:复用 UI 的正确姿势(附避坑指南)
c#·html·asp.net