1

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");
        }
    }
4

1 に答える 1