我正在玩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
让等待它的线程终止?(我不这么认为,但我认为值得一问。)