24

Is there a C# equivalent to Java's CountDownLatch?

Joey
  • 344,408
  • 85
  • 689
  • 683
Kiril
  • 39,672
  • 31
  • 167
  • 226

2 Answers2

26

The .NET Framework version 4 includes the new System.Threading.CountdownEvent class.

CesarGon
  • 15,099
  • 6
  • 57
  • 85
  • 1
    I'm going to compare both answers and I might have to award it to you (CesarGon)... it seems that yours is better, because you offer a solution that is built into C# already. – Kiril Dec 07 '09 at 01:26
  • That's fair enough, Lirik. :-) – CesarGon Dec 07 '09 at 01:28
18

Here is a simple implementation (from 9 Reusable Parallel Data Structures and Algorithms):

To build a countdown latch, you just initialize its counter to n, and have each subservient task atomically decrement it by one when it finishes, for example by surrounding the decrement operation with a lock or with a call to Interlocked.Decrement. Then, instead of a take operation, a thread could decrement and wait for the counter to become zero; when awoken, it will know that n signals have been registered with the latch. Instead of spinning on this condition, as in while (count != 0), it’s usually a good idea to let the waiting thread block, in which case you then have to use an event.

public class CountdownLatch {
    private int m_remain;
    private EventWaitHandle m_event;

    public CountdownLatch(int count) {
        m_remain = count;
        m_event = new ManualResetEvent(false);
    }

    public void Signal() {
        // The last thread to signal also sets the event.
        if (Interlocked.Decrement(ref m_remain) == 0)
            m_event.Set();
    }

    public void Wait() {
        m_event.WaitOne();
    }
}
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635