Home > Development > Tasks, Cancellation Tokens and WaitHandles

Tasks, Cancellation Tokens and WaitHandles


You can make a running task wait for a token to be cancelled by accessing the CancellationTokens WaitHandle method and Calling WaitOne on it.

This just shows you what is possible. Not neccessarily best way to do things.

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 task1 = null;
            Task task2 = null;
            try
            {

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


                task2 = new Task(() =>
                                     {
                                         Console.WriteLine("In Second Task");
                                         token.WaitHandle.WaitOne();
                                         Console.WriteLine("This will print one the task is cancelled.");
                                     }, token);

                task2.Start();

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

                task1.Wait();

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

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

    }
}

Advertisements
  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: