我注意到从 Console.CancelKeyPress 订阅然后取消订阅会使下一次订阅失败。
更奇怪的是:从一个空的事件处理程序开始可以解决这个问题。
有人可以解释这种行为吗?
class Program
{
static void Main(string[] args)
{
Console.TreatControlCAsInput = false;
// 2: uncomment following for an unexpected fix...
//Console.CancelKeyPress += (s, a) => { };
Console.CancelKeyPress += Handler_1;
Console.WriteLine("Press Ctr+C to prove that Handler_1 cancels key press.");
Console.ReadLine();
Application.DoEvents(); // make sure events are handled before unsubscribe
Console.CancelKeyPress -= Handler_1;
// 1: uncomment following to prove failure...
//Console.CancelKeyPress += Handler_2;
//Console.WriteLine("Press Ctr+C to prove that Handler_2 cancels key press.");
//Console.ReadLine();
Application.DoEvents(); // make sure events are handled
Console.WriteLine("End of demo, type something to prove application is still responsive.");
Console.ReadLine();
}
private static void Handler_1(object sender, ConsoleCancelEventArgs args)
{
args.Cancel = true;
Console.WriteLine("Key press is canceled by Handler_1");
}
private static void Handler_2(object sender, ConsoleCancelEventArgs args)
{
args.Cancel = true;
Console.WriteLine("Key press is canceled by Handler_2");
}
}