class RecursiveAutoResetEvent : IDisposable
{
private readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(true);
private int _currentThreadId;//线程ID
private int _recursionCount;//递归计数
//进入
public void Enter()
{
int threadId = Thread.CurrentThread.ManagedThreadId;
if (_currentThreadId == threadId)
{
_recursionCount++;
return;
}
_autoResetEvent.WaitOne();
_currentThreadId = threadId;
_recursionCount = 1;
}
public void Leave()
{
if (_currentThreadId != Thread.CurrentThread.ManagedThreadId) throw new InvalidOperationException();
if (--_recursionCount == 0)
{
_currentThreadId = 0;
_autoResetEvent.Set();
}
}
public void Dispose()
{
_autoResetEvent.Dispose();
}
}
|