共享锁using范围的实现方法

时间:2021-05-19

复制代码 代码如下:
/// <summary>共享锁</summary>
public class ShareLock
{
ReaderWriterLock Lock;
IDisposable readLock, writeLock;

public IDisposable ReadLock { get { Lock.AcquireReaderLock(-1); return readLock; } }
public IDisposable WriteLock { get { Lock.AcquireWriterLock(-1); return writeLock; } }
public IDisposable UpgradeLock { get { return new UpgraderLocked(Lock); } }
/// <summary>释放所有锁</summary>
public void ReleaseLock() { Lock.ReleaseLock(); }

public ShareLock()
{
this.Lock = new ReaderWriterLock();
this.readLock = new Locked(Lock.ReleaseReaderLock);
this.writeLock = new Locked(Lock.ReleaseWriterLock);
}
class Locked : IDisposable
{
ThreadStart ReleaseLock;
public Locked(ThreadStart ReleaseLock) { this.ReleaseLock = ReleaseLock; }
public void Dispose() { this.ReleaseLock(); }
}
class UpgraderLocked : IDisposable
{
delegate void ReleaseLockHandler(ref LockCookie lockCookie);

ReleaseLockHandler ReleaseLock;
LockCookie Cookie;
public UpgraderLocked(ReaderWriterLock locker)
{
Cookie = locker.UpgradeToWriterLock(-1);
this.ReleaseLock = locker.DowngradeFromWriterLock;
}
public void Dispose() { this.ReleaseLock(ref Cookie); }
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章