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: