Search code examples
c#.netwindows-servicesconsole-application

Gracefully (and controlled) exit from .NET console application


I need to convert a C# windows service (.NET Framework 4.6.1) into a console application. So this application doesn't have a real interactive interface. In the windows service application I have the OnStop() method to do the things I need before terminate... and exit.

Of course, I can create a file with a well-known name and in the console application periodically check for this file, but it seems to me an old style solution.

Is there a “best practice” to ask a console application to terminate gracefully having the time to complete the current processing?


Solution

  • So the solution I found has the following code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        class Program
        {
            private static bool keepRunning = true;
    
            public static void Main(string[] args)
            {
                Console.WriteLine("Main started");
    
                Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) {
                    e.Cancel = true;
                    keepRunning = false;
                };
    
                while (keepRunning)
                {
                    Console.WriteLine("Doing really evil things...");
    
                    System.Threading.Thread.Sleep(3000);
                }
    
                Console.WriteLine("Exited gracefully");
            }
        }
    }