Created
April 27, 2013 15:36
-
-
Save ksavelev/5473522 to your computer and use it in GitHub Desktop.
Task-based version of Stop Your Console App The Nice Way http://mikehadlow.blogspot.dk/2013/04/stop-your-console-app-nice-way.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+CodeRant+(Code+rant)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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