1

我正在玩AutoResetEvent,我的应用程序没有结束,我想我知道为什么:线程仍在运行,因此应用程序不会终止。通常,在 中Main(),我按下一个键后,应用程序就会终止。但是控制台窗口不再关闭。我有一个简单的控制台应用程序:

    private static EventWaitHandle waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AutoResetEventFun();

        Console.WriteLine("Press any key to end.");
        Console.ReadKey();

        waitHandle.Close();  // This didn't cause the app to terminate.
        waitHandle.Dispose();  // Nor did this.
    }

    private static void AutoResetEventFun()
    {
        // Start all of our threads.
        new Thread(ThreadMethod1).Start();
        new Thread(ThreadMethod2).Start();
        new Thread(ThreadMethod3).Start();
        new Thread(ThreadMethod4).Start();

        while (Console.ReadKey().Key != ConsoleKey.X)
        {
            waitHandle.Set();  // Let one of our threads process.
        }
    }

    // There are four of these methods. Only showing this one for brevity.
    private static void ThreadMethod1()
    {
        Console.WriteLine("ThreadMethod1() waiting...");

        while (true)
        {
            waitHandle.WaitOne();
            Console.WriteLine("ThreadMethod1() continuing...");   
        }
    }

终止此应用程序的正确方法是什么?我是否需要保留对每个线程的引用并调用每个线程Abort()?有没有办法发出信号waitHandle让等待它的线程终止?(我不这么认为,但我认为值得一问。)

4

2 回答 2

8

虽然我不完全确定您要完成什么,但终止此应用程序的一种方法是使所有线程后台线程:

private static void ThreadMethod1()
{ 
    Thread.CurrentThread.IsBackground = true;
    Console.WriteLine("ThreadMethod1() waiting...");

    while (true)
    {
        waitHandle.WaitOne();
        Console.WriteLine("ThreadMethod1() continuing...");   
    }
}
于 2012-09-23T03:45:01.833 回答
1

Another way is to set a volatile 'Abort' boolean flag that the threads always check after returning from the WaitOne() call to see if they need to exit. You could then set this flag and signal the WaitHandle [no. of threads] times.

于 2012-09-23T10:12:38.283 回答