// dnlib: See LICENSE.txt for more info
using System;
using System.Runtime.Serialization;
using System.Threading;
namespace dnlib.Threading {
#if THREAD_SAFE
[Serializable]
class LockException : Exception {
public LockException() {
}
public LockException(string msg)
: base(msg) {
}
protected LockException(SerializationInfo info, StreamingContext context)
: base(info, context) {
}
}
///
/// Simple class using Monitor.Enter() and Monitor.Exit()
/// and just like ReaderWriterLockSlim it prevents recursive locks. It doesn't support
/// multiple readers. A reader lock is the same as a writer lock.
///
class Lock {
readonly object lockObj;
int recurseCount;
///
/// Creates a new instance of this class
///
///
public static Lock Create() => new Lock();
///
/// Constructor
///
Lock() {
lockObj = new object();
recurseCount = 0;
}
///
/// Enter read mode
///
public void EnterReadLock() {
Monitor.Enter(lockObj);
if (recurseCount != 0) {
Monitor.Exit(lockObj);
throw new LockException("Recursive locks aren't supported");
}
recurseCount++;
}
///
/// Exit read mode
///
public void ExitReadLock() {
if (recurseCount <= 0)
throw new LockException("Too many exit lock method calls");
recurseCount--;
Monitor.Exit(lockObj);
}
///
/// Enter write mode
///
public void EnterWriteLock() {
Monitor.Enter(lockObj);
if (recurseCount != 0) {
Monitor.Exit(lockObj);
throw new LockException("Recursive locks aren't supported");
}
recurseCount--;
}
///
/// Exit write mode
///
public void ExitWriteLock() {
if (recurseCount >= 0)
throw new LockException("Too many exit lock method calls");
recurseCount++;
Monitor.Exit(lockObj);
}
}
#endif
}