1024programmer Asp.Net Lock, Monitor thread lock

Lock, Monitor thread lock

Lock, Monitor thread lock

Lock, Monitor thread lock

Official website use

https://learn.microsoft.com/zh-cn/dotnet/api/system.threading.monitor?view=net-8.0

一. Lock

1.1 Introduction

The Lock keyword is actually a syntactic sugar. It encapsulates the Monitor object and adds a mutex lock to the object. When process A enters this code segment, it will add a mutex lock to the object object. At this time, other When process B enters this code segment, check whether the object object has a lock? If there is a lock, continue to wait for process A to finish running the code segment and unlock the object object, then process B can obtain the object object, lock it, and access the code segment.
lock is syntactic sugar for Monitor

1.2 example

lock example:

private static object obj = new object();
 lock (obj)
 {
     // code logic
 }
 

二. Monitor

2.1 Introduction

Provides a mechanism for synchronous access to objects.

2.2 example

Monitor example:

private static object obj = new object();
 try
 {
     Monitor.Enter(obj);
     // code logic
 }
 catch(Exception ex)
 {
    
 }
 finally
 {
     Monitor.Exit(obj);
 }
 

The above two paragraphs of code have the same meaning
But I prefer the Monitor way of writing, because it can be more flexible.

2.3 Example

Environment: .net 7.0
Using Monitor
in WebApi
Requirements: When a thread comes in, other threads are blocked from coming in. Only after the first thread has finished executing can other threads come in.

using Microsoft.AspNetCore.Mvc;
 using System.Runtime.CompilerServices;

 namespace blog.Api.Controller.LockingMechanism
 {
     [ApiController]
     [Route("[controller]/[action]")]
     public class LockingMechanismController : ControllerBase
     {
         private static object obj = new object();
         [HttpGet]
         public JsonResult TestLock(string type)
         {

             //bool isGetLock = false;
             //bool acquiredLock = false;
             //object obj = new object();

             string msg = "Operation successful";
             int code = 200;

             bool acquiredLock = false;

             try
             {
                 Monitor.TryEnter(obj, 500, ref acquiredLock);
                 if(acquiredLock)
                 {
                     for (int i = 0; i < 10; i++)
                     {
                         Console.WriteLine("Resource is locked");
                         Thread.Sleep(1000);
                     }
                 }
                 else
                 {
                     Console.WriteLine("The lock has not been released yet, please wait");
                     JsonResult json2 = new JsonResult(new
                     {
                         code = code,
                         msg = "The lock has not been released yet, please wait",
                         type
                     });
                     //obj = new object();
                     return json2;
                 }
             }
             finally
             {
                 if(acquiredLock)
                 {
                     Monitor.Exit(obj);
                 }
                 Console.WriteLine("Resource has been released!");
             }

             JsonResult json = new JsonResult(new
             {
                 code = code,
                 msg = msg,
                 type
             });
             return json;
         }
     }
 }

 

Execute as shown below:

When thread 1 is executing, thread 2 returns and the lock is not released.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/lock-monitor-thread-lock/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索