Home > Development > Cancelling Tasks – TPL Library

Cancelling Tasks – TPL Library


We will begin by looking at a really basic example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TPLTasks
{
    public class Program
    {
        public static void Main(string[] args)
        {

            Tasks1();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public static void Tasks1()
        {

            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;

            Task t = null;

            try
            {

                t = Task.Factory.StartNew(() =>
                                                   {
                                                       for (int i = 0; i < 10000; i++)
                                                       {
                                                           token.ThrowIfCancellationRequested();
                                                           Console.WriteLine(i);
                                                       }
                                                   }, token);



                Thread.Sleep(300);
                source.Cancel();


            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Thread.Sleep(500);
            Console.WriteLine("Task Cancelled: {0}",t.IsCanceled);
        }

    }
}

To allow you tasks to be cancelled you need to create a CancellationTokenSource and then get a CancellationToken from it. Then you need to create a task and pass the token to it in its constructor. You need to manually check at periodic intervals if the token has been cancelled and throw an exception using token.ThrowIfCancellationRequested(). Outside of the task you need to call source.Cancel().

Advertisements
Categories: Development Tags: , , , , , , ,
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: