让一个线程等待n个脉冲

Tot*_*oto 12 c# multithreading

我怎么能等待n个脉冲?

… // do something
waiter.WaitForNotifications();
Run Code Online (Sandbox Code Playgroud)

我希望上面的线程等到被通知n次(由n个不同的线程或n次由同一个线程).

我相信有一种计数器可以做到这一点,但我找不到它.

dtb*_*dtb 22

看看CountdownEvent类:

CountdownEvent类

表示在计数达到零时发出信号的同步原语.

例:

CountdownEvent waiter = new CountdownEvent(n);

// notifying thread
waiter.Signal();

// waiting thread
waiter.Wait();
Run Code Online (Sandbox Code Playgroud)


xan*_*tos 8

通过使用简单ManualResetEventInterlocked.Decrement

class SimpleCountdown
{
    private readonly ManualResetEvent mre = new ManualResetEvent(false);

    private int remainingPulses;

    public int RemainingPulses
    {
        get
        {
            // Note that this value could be not "correct"
            // You would need to do a 
            // Thread.VolatileRead(ref this.remainingPulses);
            return this.remainingPulses;
        }
    }

    public SimpleCountdown(int pulses)
    {
        this.remainingPulses = pulses;
    }

    public void Wait()
    {
        this.mre.WaitOne();
    }

    public bool Pulse()
    {
        if (Interlocked.Decrement(ref this.remainingPulses) == 0)
        {
            mre.Set();
            return true;
        }

        return false;
    }
}

public static SimpleCountdown sc = new SimpleCountdown(10);

public static void Waiter()
{
    sc.Wait();
    Console.WriteLine("Finished waiting");
}

public static void Main()
{
    new Thread(Waiter).Start();

    while (true)
    {
        // Press 10 keys
        Console.ReadKey();

        sc.Pulse();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,最后,您的问题通常与其他问题有关:WaitHandle.WaitAll 64句柄限制的解决方法?

如果你没有.NET> = 4(因为另一个解决方案CountdownEvent是在.NET 4中引入的),我的解决方案很好