A day with .Net

My day to day experince in .net

Monitor Task Cancellation With Delegate

Posted by vivekcek on August 21, 2012

After we cancel a task. The delegate registered with the token will be executed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancelDelegate
{
    class Program
    {
        static CancellationTokenSource tokenSource = new CancellationTokenSource();
        static CancellationToken token = tokenSource.Token;
        static void Main(string[] args)
        {
            Task t1 = new Task(() => Iterate(), token);
            //Delegate reistartion with token
            token.Register(() => { Console.WriteLine("Task Cancellation called Message from delegate"); });
            Console.WriteLine("Task Started");
            t1.Start();
            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("Task Cancelling call");
            tokenSource.Cancel();
            try
            {
                t1.Wait();
            }
            catch (AggregateException ag)
            {
                Console.WriteLine(ag.InnerException.Message.ToString());
            }

            Console.ReadLine();
        }
        static void Iterate()
        {
            for (int i = 0; i < int.MaxValue; i++)
            {
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException("Task Cancelled Exception");
                }
                else
                {
                    Console.WriteLine(i.ToString());
                }
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s