【问题标题】:Is there a C# equivalent to Java's CountDownLatch?是否有与 Java 的 CountDownLatch 等效的 C#?
【发布时间】:2010-12-23 20:34:50
【问题描述】:

是否有与 Java 的 CountDownLatch 等效的 C#?

【问题讨论】:

    标签: c# multithreading synchronization countdownlatch


    【解决方案1】:

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

    【讨论】:

    • 我将比较这两个答案,我可能不得不将它授予您(CesarGon)...看来您的更好,因为您提供了一个已经内置于 C# 中的解决方案。
    • 这很公平,Lirik。 :-)
    【解决方案2】:

    这是一个简单的实现(来自9 Reusable Parallel Data Structures and Algorithms):

    要构建倒计时锁,您只需 将其计数器初始化为 n,并有 每个从属任务原子地 完成后减一, 例如通过包围 带锁的减量操作或 调用 Interlocked.Decrement。 然后,不是 take 操作,而是一个 线程可以递减并等待 计数器变为零;什么时候 醒来,它会知道有 n 个信号 已在闩锁中注册。 而不是在这种情况下旋转, 如 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 2018-11-20
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多