1

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?

Tonyc
  • 709
  • 1
  • 10
  • 29
  • 1
    Check for Ctrl-C on the console, and when it is detected, run your ``OnStop()`` method? – dumetrulo Nov 21 '18 at 14:21
  • Yes... it's a simple and direct solution, thanks. I found a simple code to do it at this [link](https://stackoverflow.com/questions/177856/how-do-i-trap-ctrl-c-in-a-c-sharp-console-app) – Tonyc Nov 21 '18 at 14:46

1 Answers1

1

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");
        }
    }
}
Tonyc
  • 709
  • 1
  • 10
  • 29