CountdownLatch.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Threading;
  3. namespace Utilities
  4. {
  5. public class CountdownLatch
  6. {
  7. private int m_count;
  8. private EventWaitHandle m_waitHandle = new EventWaitHandle(true, EventResetMode.ManualReset);
  9. public CountdownLatch()
  10. {
  11. }
  12. public void Increment()
  13. {
  14. int count = Interlocked.Increment(ref m_count);
  15. if (count == 1)
  16. {
  17. m_waitHandle.Reset();
  18. }
  19. }
  20. public void Add(int value)
  21. {
  22. int count = Interlocked.Add(ref m_count, value);
  23. if (count == value)
  24. {
  25. m_waitHandle.Reset();
  26. }
  27. }
  28. public void Decrement()
  29. {
  30. int count = Interlocked.Decrement(ref m_count);
  31. if (m_count == 0)
  32. {
  33. m_waitHandle.Set();
  34. }
  35. else if (count < 0)
  36. {
  37. throw new InvalidOperationException("Count must be greater than or equal to 0");
  38. }
  39. }
  40. public void WaitUntilZero()
  41. {
  42. m_waitHandle.WaitOne();
  43. }
  44. }
  45. }