我已经编写了我希望在C#/ .NET中使用ManualResetEvent和AutoResetEvent类的轻量级替代方法.这背后的原因是让事件像功能一样没有使用内核锁定对象的重量.
尽管代码似乎在测试和生产中都运行良好,但是对于所有可能性来说,这种方法都是正确的,这可能是一件令人担忧的事情.我会谦卑地请求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);
} …Run Code Online (Sandbox Code Playgroud)