遊んでいて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
それを待っているスレッドが終了するように信号を送る方法はありますか?(私はそうは思いませんが、尋ねる価値があると思いました。)