📄 lightlock.cs
字号:
namespace NCindy.Util
{
using System;
using System.Threading;
public sealed class LightLock : IDisposable
{
private bool isDisposed = false;
private const int LockIsFree = 0;
private const int LockIsOwned = 1;
private int lockState;
private readonly Semaphore waiterLock = new Semaphore(0, 0x7fffffff);
private const int WaitersCountBase = 2;
private void CheckDisposed()
{
if (this.isDisposed)
{
throw new ObjectDisposedException(null);
}
}
public void Dispose()
{
this.CheckDisposed();
try
{
this.waiterLock.Close();
}
finally
{
this.isDisposed = true;
}
}
public void Enter()
{
this.Enter(-1);
}
public void Enter(int timeout)
{
this.CheckDisposed();
Thread.BeginCriticalRegion();
while (true)
{
int ifThisEqualsToValue = InterlockedHelper.Or(ref this.lockState, 1);
if ((ifThisEqualsToValue & 1) == 0)
{
return;
}
if (InterlockedHelper.CompareAndExchange(ref this.lockState, ifThisEqualsToValue, ifThisEqualsToValue + 2))
{
this.waiterLock.WaitOne(timeout, false);
}
}
}
public void Exit()
{
this.CheckDisposed();
int num = InterlockedHelper.And(ref this.lockState, -2);
if (num != 1)
{
num &= -2;
if (InterlockedHelper.CompareAndExchange(ref this.lockState, num & -2, num - 2))
{
this.waiterLock.Release(1);
}
}
Thread.EndCriticalRegion();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -