我正在构建一个简单的控制台应用程序,它可以启动一个计时器并执行一些操作。如果用户按下 Ctrl-C,我想关闭。
当我对此进行编码时,应用程序检测到 Ctrl-C,但随后挂起并且永远不会关闭。我做错了什么?
代码如下:
using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
private static readonly AutoResetEvent _closeEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("Hello World - waiting for Ctrl-C");
Console.CancelKeyPress += (sender, eventArgs) =>
{
Console.WriteLine("Got the Ctrl-C");
_closeEvent.Set();
};
// Start up a timer and do work here...
Console.WriteLine("Before WaitOne");
_closeEvent.WaitOne();
Console.WriteLine("After WaitOne");
}
}
}
我想知道这是否只是 Visual Studio 调试器的副作用?如果我在不调试的情况下运行它,然后按 Ctrl-C,控制台会显示“按任意键继续...”,然后按任意键终止应用程序。
最佳答案
看来要搞定这个工作的关键是设置
eventArgs.Cancel = true;
在 CancelKeyPress
处理程序中。
然后一切正常,应用程序正确终止。
关于c# - 为什么我的 .NET 控制台应用程序在等待 Ctrl-C 时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991578/