CSharp examples for Thread Asynchronous:Task
Cancel a Task
using System;/*w ww.ja v a 2s . c o m*/ using System.Threading; using System.Threading.Tasks; class MainClass { static void Main(string[] args) { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task task = Task.Factory.StartNew(() => printNumbers(token), token); token.Register(() => notifyTaskCancelled()); Console.WriteLine("Press enter to cancel token"); Console.ReadLine(); tokenSource.Cancel(); } static void notifyTaskCancelled() { Console.WriteLine("Task cancellation requested"); } static void printNumbers(CancellationToken token) { int i = 0; while (!token.IsCancellationRequested) { Console.WriteLine("Number {0}", i++); Thread.Sleep(500); } throw new OperationCanceledException(token); } }