LoginSignup
8
5

More than 5 years have passed since last update.

Ctrl+Cで終了できるけど切りのいいところまでは待つコンソールアプリ

Posted at

今回はWindowsコンソールアプリで。他でもできるかもしれんけど。

コンソールアプリは、Ctrl+Cで処理を中止できるのはご存知だと思います。
でも、大事な処理の途中で止まるのは困るわけで。

Ctrl+Cで処理を中止しようとするとConsole.CancelKeyPressイベントが来るので、そこで中止を中止することができます。

Program.cs
using System;
using System.Threading;

namespace ExitTiming
{
    class Program
    {
        private bool running = true;

        private void Run()
        {
            // 中断の割り込みがあったときのイベントを受け取る
            Console.CancelKeyPress += Console_CancelKeyPress;

            // 続く限り続く
            while (running)
            {
                // 動いてるアピール
                Console.WriteLine(DateTime.Now);

                // 何か時間のかかる処理のつもり
                Thread.Sleep(5000);
            }
        }

        private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            // 中断を受け付けましたアピール
            Console.WriteLine("Ctrl+C");

            // もう頑張らなくていいことをメイン処理に伝える
            running = false;

            // 今は終わらんよと伝える
            e.Cancel = true;
        }

        static void Main(string[] args)
        {
            new Program().Run();
        }
    }
}

Windows 10
Visual Studio 2017
.NET Framework 4.6.2
C#

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5