为什么这个短程序永远不会完成?

And*_*son 3 .net c# waithandle

通过调试我自己的问题,我设法重新创建了一个非常不寻常的小程序:

using System;
using System.Threading;

namespace CancelBug
{
    class Program
    {
        static void Main(string[] args)
        {
            var unused = new ManualResetEvent(false);
            var cancelled = new ManualResetEvent(false);
            Console.CancelKeyPress += (s, e) => cancelled.Set();
            Console.WriteLine("Running. The only thing to do now is ctrl+c or close the window...");
            WaitHandle.WaitAny(new[] { unused, cancelled });
            Console.WriteLine("Press enter to continue...");
            Console.Read();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这个程序能够:

  • 显示第一行
  • 等到用户尝试退出程序
  • 显示第二行
  • 等到用户按下回车键
  • 出口

然而,一旦这使它通过调用WaitHandle.WaitAny,它似乎挂在随机线上.有时最后一行永远不会被打印出来,有时它会被打印,但是输入键永远不会被读取.使用更大的代码库,它可以执行更多代码行,并且仍然挂在看似随机的位置.

谁能解释这种奇怪的行为?

Fre*_*gar 8

您需要取消该CTRL+C命令,否则您的流程将被终止:

Console.CancelKeyPress += (s, e) =>
{
    e.Cancel = true;
    cancelled.Set();
};
Run Code Online (Sandbox Code Playgroud)

来自https://msdn.microsoft.com/en-us/library/system.consolecanceleventargs(v=vs.110).aspx:

如果在事件处理程序中将Cancel属性设置为true,则恢复该进程; 否则,该过程终止.默认情况下,ConsoleCancelEventArgs属性的值为false,并且该进程终止.