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

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

相关推荐
kybs19917 小时前
springboot视频推荐系统--附源码72953
java·spring boot·python·eclipse·asp.net·php·idea
William_cl4 天前
【C#/.NET 进阶】ASP.NET 架构与最佳实践:DI 依赖注入(IoC 核心)从入门到避坑
c#·asp.net·.net
医疗信息化王工11 天前
基于ASP.NET Core的医院不良事件管理系统的架构设计
后端·asp.net
余衫马13 天前
在 Windows 服务中托管 ASP.NET Core Web API (.net6)
运维·windows·后端·asp.net·.net
波波00718 天前
ASP.NET Core 健康检查实战:不只是一个 /health 接口
后端·asp.net
csdn_aspnet19 天前
了解 ASP.NET Core 中的防伪技术
后端·asp.net·csrf·.net core
叫我黎大侠19 天前
.NET 实战:调用千问视觉模型实现 OCR(车票识别完整教程)
阿里云·ai·c#·ocr·asp.net·.net·.netcore
William_cl23 天前
C# ASP.NET 分层架构实战:BLL (Service) 业务层从入门到封神(规范 + 避坑)
架构·c#·asp.net
无风听海24 天前
.NET10之内置日志配置与使用指南
asp.net·.net
csdn_aspnet25 天前
在 ASP.NET Core (WebAPI) 中启用 CORS
后端·asp.net·.netcore