Last active
September 6, 2015 20:46
-
-
Save tarasn/024efdaf19a3aa0a2894 to your computer and use it in GitHub Desktop.
[TPL] Task cancellation
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 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