我已经编写了我希望是在 C#/.NET 中使用 ManualResetEvent 和 AutoResetEvent 类的轻量级替代方案。这背后的原因是具有类似事件的功能,而无需使用内核锁定对象。
尽管代码似乎在测试和生产中都运行良好,但为所有可能性正确处理这种事情可能是一项艰巨的任务,我会谦虚地请求 StackOverflow 人群对此提出任何建设性意见和或批评。希望(经过审查)这对其他人有用。
用法应该类似于用于 Set() 的具有 Notify() 的 Manual/AutoResetEvent 类。
开始:
using System;
using System.Threading;
public class Signal
{
private readonly object _lock = new object();
private readonly bool _autoResetSignal;
private bool _notified;
public Signal()
: this(false, false)
{
}
public Signal(bool initialState, bool autoReset)
{
_autoResetSignal = autoReset;
_notified = initialState;
}
public virtual void Notify()
{
lock (_lock)
{
// first time?
if (!_notified)
{
// set the flag
_notified = true;
// unblock a thread which is waiting on this signal
Monitor.Pulse(_lock);
}
}
}
public void Wait()
{
Wait(Timeout.Infinite);
}
public virtual bool Wait(int milliseconds)
{
lock (_lock)
{
bool ret = true;
// this check needs to be inside the lock otherwise you can get nailed
// with a race condition where the notify thread sets the flag AFTER
// the waiting thread has checked it and acquires the lock and does the
// pulse before the Monitor.Wait below - when this happens the caller
// will wait forever as he "just missed" the only pulse which is ever
// going to happen
if (!_notified)
{
ret = Monitor.Wait(_lock, milliseconds);
}
if (_autoResetSignal)
{
_notified = false;
}
return (ret);
}
}
}