c# - CountDownEvent 不会等到所有信号都被调用

标签 c# multithreading countdownevent

我在这个网站上寻找 threads . 我一直在玩代码来回答“CountdownEvent 是否停止所有线程?”这个问题。 我得到的答案是否定的。然后我决定使用传递给 CountdownEvent 的数字。这是我的代码

namespace ThreadPractice
{
    class Program
    {
        static CountdownEvent CountDown = new CountdownEvent(4);
        static void Main()
        {
            new Thread(() => SaySomething("I am Thread one.")).Start();
            new Thread(() => SaySomething("I am thread two.")).Start();
            new Thread(() => SaySomethingElse("Hello From a different Thread")).Start();
            new Thread(() => SaySomething("I am Thread Three.")).Start();
            CountDown.Wait();
            Console.Read();
        }

        static void SaySomething(string Something)
        {
            Thread.Sleep(1000);
            Console.WriteLine(Something);
            CountDown.Signal();
        }

        static void SaySomethingElse(string SomethingElse)
        {
            Thread.Sleep(1000);
            Console.WriteLine(SomethingElse);
        }
    }
}

我期望调用 SaySomethingELse() 的线程执行,但其他线程也执行,即使只调用了四个信号。

为什么要这样做?

谢谢,

多哈

最佳答案

在我看来,您的 SignalWait 方向不对。如果您希望 SaySomething 调用等待倒计时达到 0,您应该调用 Wait。这是一个例子:

using System;
using System.Threading;

namespace ThreadPractice
{
    class Program
    {
        static CountdownEvent CountDown = new CountdownEvent(4);
        static void Main()
        {
            new Thread(() => SaySomething("I am Thread one.")).Start();
            new Thread(() => SaySomething("I am thread two.")).Start();
            new Thread(() => SaySomethingElse("Hello From a different Thread")).Start();
            new Thread(() => SaySomething("I am Thread Three.")).Start();
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("Calling Signal (time #{0})", i);
                CountDown.Signal();
                Thread.Sleep(1000);
            }
            Console.WriteLine("Done"); 
        }

        static void SaySomething(string Something)
        {
            CountDown.Wait();
            Console.WriteLine(Something);
        }

        static void SaySomethingElse(string SomethingElse)
        {
            Thread.Sleep(1000);
            Console.WriteLine(SomethingElse);
        }
    }
}

输出:

Calling Signal (time #0)
Hello From a different Thread
Calling Signal (time #1)
Calling Signal (time #2)
Calling Signal (time #3)
I am Thread one.
I am Thread Three.
I am thread two.
Done

关于c# - CountDownEvent 不会等到所有信号都被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530058/

相关文章:

c# - 就地排序 List<Tuple<int, int>>

java - 为什么要减小 Java JVM 线程栈的大小?

java - 如何使用 ThreadPoolTask​​Executor 获取线程状态?

c# - 归零CountdownEvent

c# - 如何在 View 模型中的 View 上使用路由命令

c# - _Layout.cshtml 上的 MVC 决策

android - 如何在不使用 CountDownTimer 的情况下创建倒计时时钟

c# - 如何从 3 个 double 列表中获取 float 组?

c# - 自动并行化策略