Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Created November 19, 2017 19:37
Show Gist options
  • Save luisdeol/2605abee73aacfb003e6eaedaa1a5a2c to your computer and use it in GitHub Desktop.
Save luisdeol/2605abee73aacfb003e6eaedaa1a5a2c to your computer and use it in GitHub Desktop.
Using the CancellationToken
namespace manage_multithreading
{
class Program
{
static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
int theCount = 0;
Console.WriteLine("Task running...Count from 0 to...");
Console.WriteLine("Press ENTER to interrupt the execution!");
Task theIncredibleTask = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
Thread.Sleep(1000);
Console.WriteLine(theCount.ToString());
theCount++;
}
}, token);
Console.ReadLine();
cancellationTokenSource.Cancel();
Console.WriteLine("Execution cancelled!");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment