Я написал, как я надеюсь, легкую альтернативу использованию классов ManualResetEvent и AutoResetEvent в C # /. NET. Причиной этого было использование функциональности, подобной Event, без необходимости использования объекта блокировки ядра.
Хотя кажется, что код хорошо работает как в тестировании, так и в производстве, правильно подобрать такую штуку для всех возможностей может быть чреватым трудом, и я смиренно прошу любые конструктивные комментарии и критику со стороны группы StackOverflow по этому поводу. Надеюсь (после обзора) это будет полезно другим.
Использование должно быть аналогично классам Manual / AutoResetEvent с Notify (), используемым для Set ().
Вот так:
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);
}
}
}