A day with .Net

My day to day experince in .net

Cancelling Tasks

Posted by vivekcek on August 19, 2012

I hope you have some experience with Thread Pool in .net. We can queue work items to thread pool and wait for all to complete. But it was very hard to control the queued work items. So here comes TPL. We can cancel a task when it is working. Try out this code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancel
{
    class Program
    {
        static CancellationTokenSource tokenSource ;
        static CancellationToken token;
        static void Main(string[] args)
        {

            tokenSource = new CancellationTokenSource();
            token = tokenSource.Token;
            Task t1 = new Task(() => iterate(),token);
            t1.Start();
            System.Threading.Thread.Sleep(100);
            tokenSource.Cancel();
            Console.ReadLine();
        }

        static void iterate()
        {
           
                for (int i = 0; i < int.MaxValue; i++)
                {
                    if (token.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }
                    else
                    {
                        Console.WriteLine(i);
                    }
                }
            
        }
        
    }
}
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