如何在.NET 4中使用Console.CancelKeyPress? (在.NET 3.5及更低版本中工作良好) [英] How do I use Console.CancelKeyPress in .NET 4? (Works fine in .NET 3.5 and below)

查看:271
本文介绍了如何在.NET 4中使用Console.CancelKeyPress? (在.NET 3.5及更低版本中工作良好)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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/net-4-control-c-event-handler-broken/

It seems this person is seeing the same issue: http://johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/

推荐答案

这是 Microsoft Connect

请注意,它在调试器之外工作。

Note that it does work outside of the debugger.

这篇关于如何在.NET 4中使用Console.CancelKeyPress? (在.NET 3.5及更低版本中工作良好)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆