考虑一个控制台应用程序,它在单独的线程中启动一些服务。 它所需要做的就是等待用户按下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
}
bool
未声明为volatile
,因此在while
循环中对_quitFlag
的后续读取可能会被优化掉,导致无限循环。 - Adam Robinson