Big*_*714 10 c# console .net-4.0
我正在C#4中编写一个Console应用程序,想要优雅地取消我的程序并按下Ctrl + C. 我之前使用过很多次代码,但是现在尝试在.NET 4中使用它时,似乎发生了一个奇怪的未处理异常.
namespace ConsoleTest
{
class Program
{
private static bool stop = false;
static void Main(string[] args)
{
System.Console.TreatControlCAsInput = false;
System.Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
while (!stop)
{
System.Console.WriteLine("waiting...");
System.Threading.Thread.Sleep(1000);
}
System.Console.WriteLine("Press any key to exit...");
System.Console.ReadKey(true);
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
stop = true;
e.Cancel = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将目标框架更改为.NET 3.5,它可以工作.
编辑:看来这个人看到了同样的问题:http: //johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/