別のスレッドでいくつかのサービスを起動するコンソールアプリケーションについて考えてみます。ユーザーがCtrl+Cを押してシャットダウンするのを待つだけです。
これを行うためのより良い方法は次のうちどれですか?
static ManualResetEvent _quitEvent = new ManualResetEvent(false);
static void Main() {
Console.CancelKeyPress += (sender, eArgs) => {
_quitEvent.Set();
eArgs.Cancel = true;
};
// kick off asynchronous stuff
_quitEvent.WaitOne();
// cleanup/shutdown and quit
}
または、Thread.Sleep(1)を使用して:
static bool _quitFlag = false;
static void Main() {
Console.CancelKeyPress += delegate {
_quitFlag = true;
};
// kick off asynchronous stuff
while (!_quitFlag) {
Thread.Sleep(1);
}
// cleanup/shutdown and quit
}