我如何使用Console.CancelKeyPress在.NET 4? (在.NET 3.5及以下正常工作) [英] How do I use Console.CancelKeyPress in .NET 4? (Works fine in .NET 3.5 and below)
问题描述
我写在C#4控制台应用程序,并希望优雅地取消我的程序,并按下Ctrl + C键。下面的代码我以前用过很多次,但现在正试图在.NET 4中使用它的时候,它似乎是一个奇怪的未处理的异常发生。
I am writing a Console app in C# 4 and want to gracefully cancel my program and Ctrl + C is pressed. The following code I have used many times before, but now when trying to use it in .NET 4, it seems a strange unhandled exception is occurring.
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;
}
}
}
如果我改变目标框架.NET 3.5,它的工作原理
编辑:看来这个人是看到了同样的问题:
http://johnwheatley.wordpress.com/ 2010/04/14 /净-4-控制C-事件处理破碎/
It seems this person is seeing the same issue: http://johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/
推荐答案
这是的 Microsoft连接。
请注意,它确实在调试器之外的工作。
Note that it does work outside of the debugger.
这篇关于我如何使用Console.CancelKeyPress在.NET 4? (在.NET 3.5及以下正常工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!