using System; using System.Threading; namespace Common { public class CountDownLatch { private int remainingCount; private EventWaitHandle waitEventHandle; public EventWaitHandle WaitEventHandle => waitEventHandle; public CountDownLatch(int count) { Reset(count); } public void Reset(int count) { if (count < 0) throw new ArgumentOutOfRangeException(); remainingCount = count; waitEventHandle = new ManualResetEvent(false); if (remainingCount == 0) { waitEventHandle.Set(); } } public void Signal() { // The last thread to signal also sets the event. if (Interlocked.Decrement(ref remainingCount) == 0) waitEventHandle.Set(); } public void Wait() { waitEventHandle.WaitOne(); } } }