我正在C#4中编写一个控制台应用程序,并希望正常地取消我的程序,并按下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;
- }
- }
- }
如果我将目标框架更改为.NET 3.5,它可以正常工作.
编辑:看来这个人看到同样的问题:
http://johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/
解决方法
这是
Microsoft Connect的一个已知问题.
请注意,它在调试器之外工作.