首页 > 解决方案 > 为什么这个小程序永远不会完成?

问题描述

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

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();
        }
    }
}

我希望这个程序能够:

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

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

标签: c#.netwaithandle

解决方案


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

Console.CancelKeyPress += (s, e) =>
{
    e.Cancel = true;
    cancelled.Set();
};

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

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


推荐阅读