c# - 为什么这个小程序永远不会完成?
问题描述
通过调试我自己的问题,我设法重新创建了一个行为异常的小程序:
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,并且进程终止。
推荐阅读
- angular - 如何将订阅内容传递到 CanDeactivateGuard
- c++ - 以相反的顺序打印数组 - 为什么在 C++ 中这是错误的?
- c - 如何使用strtok和指针读取txt文件并逐行逐字分割?
- mysql - #1064 - 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以获取在 '' 附近使用的正确语法
- regex - 查找正则表达式
- javascript - 是否可以使用 javascript 将字体动态更改为自定义字体?
- java - 将json数据ajax传递给Spring boot
- jquery - 为什么 Asp.net Core 无法读取 Ajax 参数?
- json - jq unique_by 选择排序后的第一个元素
- javascript - 为什么我不能从另一个文件中的一个文件访问全局范围变量?