Skip to content

Instantly share code, notes, and snippets.

@ksavelev
Created April 27, 2013 15:36
Show Gist options
  • Save ksavelev/5473522 to your computer and use it in GitHub Desktop.
Save ksavelev/5473522 to your computer and use it in GitHub Desktop.
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");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment