【问题标题】:AutoResetEvent clarificationAutoResetEvent 说明
【发布时间】:2009-11-24 13:03:29
【问题描述】:

我想澄清以下代码的工作原理。我已逐项列出我的疑问以获得您的回复。

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();
    }
}
  1. static AutoResetEvent autoEvent = new AutoResetEvent(false);

    在初始阶段信号设置为假。

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

    从 ThreadPool 中选择一个线程并让该线程执行 CodingInCSharp。 WaitCallback 的目的是执行 Main() 线程之后的方法 完成它的执行。

  3. autoEvent.WaitOne(1000,false)

    等待 1 秒从“CodingInCSharp”获取信号) 如果我使用 WaitOne(1000,true),它会杀死它收到的线程吗 线程池?

  4. 如果我没有设置((AutoResetEvent)stateInfo).Set();,Main() 会无限期地等待信号吗?

【问题讨论】:

    标签: c# multithreading


    【解决方案1】:

    一旦线程池线程可用,WaitCallback 就会在并发中执行到 Main 方法。

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

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

    如果没有设置信号,Main 方法不会无限等待,因为如果在 1 秒内没有设置信号,等待信号就会中止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-01
      • 2011-01-04
      • 2015-04-03
      • 2013-10-19
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多