今回は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#