简体   繁体   English

是否有一个C#等同于Java的CountDownLatch?

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

是否有一个C#等同于Java的CountDownLatch

.NET Framework版本4包含新的System.Threading.CountdownEvent类。

Here is a simple implementation (from 9 Reusable Parallel Data Structures and Algorithms ): 这是一个简单的实现(来自9个可重用的并行数据结构和算法 ):

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. 要构建倒计时锁存器,只需将其计数器初始化为n,并使每个子服务任务在完成时以原子方式将其减1,例如通过使用锁定或通过调用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. 当被唤醒时,它将知道已经向锁存器登记了n个信号。 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. 而不是在这种情况下旋转,就像在while(count!= 0)中一样,让等待的线程阻塞通常是一个好主意,在这种情况下你必须使用一个事件。

 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(); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM