![](/img/trans.png)
[英]Why does my program for finding the largest prime never writes to console?
[英]Why does this short program never complete?
通过调试我自己的问题,我设法重新创建了一个非常不寻常的小程序:
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
,它似乎挂在随机行上。 有时最后一行永远不会被打印出来,有时它会被打印,但是输入键永远不会被读取。 使用更大的代码库,它可以执行更多代码行,并且仍然挂在看似随机的位置。
谁能解释这种奇怪的行为?
您需要取消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,并且该进程终止。
Ctrl + C
是关闭命令窗口的全局命令。 因此,此组合键将在实际程序结束之前关闭窗口。 尝试使用其他密钥。
请在没有调试器的情况下运行应用程序(直接从命令行)。
根据我的测试,这是我的测试应用程序,其行为与您期望的一样。
var cancelled = new ManualResetEvent(false);
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
Console.WriteLine("Ctrl+C detected...");
cancelled.Set();
};
Console.WriteLine("Running. The only thing to do now is ctrl+c or close the window...");
WaitHandle.WaitAny(new[] { cancelled });
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.