Task-based version of
Stop Your Console App The Nice Way
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");
}
}
}