cicorias
3/26/2019 - 2:00 PM

Task-based version of Stop Your Console App The Nice Way http://mikehadlow.blogspot.dk/2013/04/stop-your-console-app-nice-way.html?ut

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Mike.Spikes.ConsoleShutdown
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Application has started. Ctrl-C to end");

            var cSource = new CancellationTokenSource();
            var myTask = Task.Factory.StartNew(() => Worker(cSource.Token), cSource.Token); // TaskCreationOptions.LongRunning?
            
            Console.CancelKeyPress += (sender, eventArgs) => cSource.Cancel();

            myTask.Wait();

            Console.WriteLine("Now shutting down");
        }

        private static void Worker(CancellationToken cToken)
        {
            while (!cToken.IsCancellationRequested)
            {
                Console.WriteLine("Worker is working");
                Thread.Sleep(1000);
            }

            Console.WriteLine("Worker thread ending");
        }
    }
}