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

发布于 2024-08-13 21:44:39 字数 154 浏览 2 评论 0原文

是否有相当于 Java 的 倒计时锁

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

べ映画 2024-08-20 21:44:39

.NET Framework 版本 4 包括新的 系统.Threading.CountdownEvent 类。

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

苦行僧 2024-08-20 21:44:39

这是一个简单的实现(来自9个可重用的并行数据结构和算法):

要构建倒计时锁存器,您只需
将其计数器初始化为 n,并且有
每个从属任务都是原子的
完成后减一,
例如通过围绕
带锁的减量操作或
调用 Interlocked.Decrement。
然后,代替 take 操作,
线程可以递减并等待
计数器变为零;什么时候
醒来后,它会知道n个信号
已向闩锁注册。
而不是在这种情况下旋转,
就像 while (count != 0) 一样,通常是
让等待线程是个好主意
阻止,在这种情况下你必须
使用事件。

公共类 CountdownLatch {
    私有 int m_remain;
    私有EventWaitHandle m_event;

    公共 CountdownLatch(int 计数) {
        m_remain = 计数;
        m_event = new ManualResetEvent(false);
    }

    公共无效信号(){
        // 最后发出信号的线程也设置事件。
        if (Interlocked.Decrement(ref m_remain) == 0)
            m_event.Set();
    }

    公共无效等待(){
        m_event.WaitOne();
    }
}

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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文