Skip to content

Instantly share code, notes, and snippets.

@tarasn
Last active September 6, 2015 20:46
Show Gist options
  • Save tarasn/024efdaf19a3aa0a2894 to your computer and use it in GitHub Desktop.
Save tarasn/024efdaf19a3aa0a2894 to your computer and use it in GitHub Desktop.
[TPL] Task cancellation
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var t = Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(500);
if (token.IsCancellationRequested)
{
//cleanup
Console.WriteLine("Canceled");
token.ThrowIfCancellationRequested();
}
Console.WriteLine("500 milliseconds passed");
}
}, token);
cts.CancelAfter(TimeSpan.FromSeconds(10));
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment