Cancel a Task - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Cancel a Task

Demo Code


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);
        }
    }

Result


Related Tutorials