c# - AutoResetEvent澄清

标签 c# multithreading

我想澄清以下代码的工作方式。我逐一列出了我的疑问,以得到您的答复。

class AutoResetEventDemo
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("...Main starting...");

        ThreadPool.QueueUserWorkItem
        (new WaitCallback(CodingInCSharp), autoEvent);

        if(autoEvent.WaitOne(1000, false))
        {
            Console.WriteLine("Coding singalled(coding finished)");
        }
        else
        {
            Console.WriteLine("Timed out waiting for coding"); 
        }

        Console.WriteLine("..Main ending...");

        Console.ReadKey(true);
    }

    static void CodingInCSharp(object stateInfo) 
    {
        Console.WriteLine("Coding Begins.");
        Thread.Sleep(new Random().Next(100, 2000));
        Console.WriteLine("Coding Over");
       ((AutoResetEvent)stateInfo).Set();
    }
}
  • static AutoResetEvent autoEvent = new AutoResetEvent(false);
    在初始阶段,信号设置为假。
  • ThreadPool.QueueUserWorkItem(new WaitCallback(CodingInCSharp), autoEvent);
    从ThreadPool中选择一个线程,并使该线程执行CodingInCSharp。
    WaitCallback的目的是在Main()线程之后执行该方法
    完成执行。
  • autoEvent.WaitOne(1000,false)
    等待1秒钟,以从“CodingInCSharp”获得信号)
    如果我使用WaitOne(1000, true ),它将杀死从它接收到的线程
    线程池?
  • 如果未设置((AutoResetEvent)stateInfo).Set();,Main()将无限期地等待信号吗?
  • 最佳答案

    线程池线程可用后,将在中同时在中执行WaitCallback到Main方法。

    Main方法在线程池线程上等待1秒钟以等待CodingInCSharp方法设置信号。如果在1秒钟内设置了信号,则Main方法将输出"Coding singalled(coding finished)"。如果未在1秒钟内设置信号,则Main方法将中止等待信号并打印"Timed out waiting for coding"。在这两种情况下,Main方法都会继续等待按键被按下。

    设置信号或达到超时不会“杀死”线程。

    如果未设置信号,Main方法将不会无限期等待,因为如果未在1秒钟内设置信号,则等待信号将中止。

    关于c# - AutoResetEvent澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787816/

    相关文章:

    c# - Visual Studio 2010 只能运行 4.0 单元测试吗?

    c# - 用于选择包含所有字母的字符串的 Linq 语句

    c# - 最小 Web Api 未返回所需结果

    multithreading - Spring + Hibernate 跨多个线程的 session 管理

    multithreading - OpenMP 和shared_ptr

    c# - 如何拦截WCF Web方法请求?

    c# - Dapper 映射结果列表

    python - 线程之间的简单字节流是否需要 Python 队列?

    c++ - 我应该如何在一个函数中锁定 wxMutex 并在另一个函数中解锁它?

    multithreading - 如何才能充分利用 .NET 4.0 中新增强的并行功能?