1

I All,

I have to monitor an async task, which has to be cancellable and do not perform more than specific Time To Live.

I already knew about the following code.

CancellationTokenSource l_cts = new CancellationTokenSource(timemillis);

which will doing the cancellation ( as far i monitor the token in my async method). However, this NOT gave me any information about WHY he has been cancelled, Timeout or user cancellation? furthermore, the timeout event is delayed while i did not catch the cancellation with

Token.ThrowIfCancellationRequested();

In order to solve these issues, I wrote the timeout process as follow.

    static async Task TestAsync(int processDelaySeconds, int cancelDelaySeconds, int timeoutDelaySeconds )
    {
        CancellationTokenSource l_cts = new CancellationTokenSource();

        // the process to monitor
        Task l_process = new Task((state) =>
        {
            Console.WriteLine("Process BEGIN");
            // dummy loop
            for (int l_i = 0; l_i != processDelaySeconds; l_i++)
            {
                Thread.Sleep(1000);
                l_cts.Token.ThrowIfCancellationRequested();
            }
            Console.WriteLine("Process END");
        }, null, l_cts.Token);

        // register timeout
        RegisteredWaitHandle l_rwh = ThreadPool.RegisterWaitForSingleObject(l_cts.Token.WaitHandle,
                (state, timedOut) =>
                {
                    if (timedOut)
                    {
                        l_cts.Cancel();
                        Console.WriteLine("Timed out");
                    }
                    else
                    {
                        Console.WriteLine("Cancel Signaled");
                    }
                },
                null, (int)TimeSpan.FromSeconds(timeoutDelaySeconds).TotalMilliseconds, true);

        // cancel task
        if (cancelDelaySeconds > 0)
        {
            Task l_cancel = new Task(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(cancelDelaySeconds));
                l_cts.Cancel();
            });

            l_cancel.Start();
        }

        try
        {
            l_process.Start();
            await l_process;
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Task Cancelled");
        }
        finally
        {
            // be sure to unregister the wait handle to cancel the timeout
            if (l_process.Status != TaskStatus.Canceled) l_rwh.Unregister(l_cts.Token.WaitHandle);
        }

        Console.WriteLine("Task Status is : {0}", l_process.Status);
    }  

    static async void Tests()
    {
        Console.WriteLine("NORMAL PROCESS");
        Console.WriteLine("--------------");
        await TestAsync(2, 10, 10);

        Console.WriteLine();
        Console.WriteLine("CANCEL");
        Console.WriteLine("------");
        await TestAsync(5, 2, 10);

        Console.WriteLine();
        Console.WriteLine("TIMEOUT");
        Console.WriteLine("-------");
        await TestAsync(10, 15, 2); 
    }

Then My question is : Is there any drawbacks or traps behind the scene ? A better and more efficient way ??

ps- Goal is performance, not shorter code.

2
  • You should use Task.Delay instead of Thread.Sleep if you want to delay execution. Especially if you are looking for performance.
    – Stilgar
    Apr 27, 2014 at 18:00
  • Probably better fit for : http://programmers.stackexchange.com/
    – Noctis
    Apr 28, 2014 at 1:30

2 Answers 2

3

If you need to distinguish between the user's and time-out cancellation, you can use CreateLinkedTokenSource:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    internal class Program
    {
        // worker
        private static void DoWork(CancellationToken token)
        {
            for (int i = 0; i < 1000; i++)
            {
                token.ThrowIfCancellationRequested();
                Thread.Sleep(100); // do the work item
            }
            token.ThrowIfCancellationRequested();
        }

        // test
        private static void Main()
        {
            var userCt = new CancellationTokenSource();
            var combinedCt = CancellationTokenSource.CreateLinkedTokenSource(
                userCt.Token);
            combinedCt.CancelAfter(3000); // cancel in 3 seconds

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                userCt.Cancel();
            };

            var task = Task.Run(
                () => DoWork(combinedCt.Token), 
                combinedCt.Token);

            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                Console.WriteLine(ex.InnerException.Message);
                if (task.IsCanceled)
                {
                    if (userCt.Token.IsCancellationRequested)
                        Console.WriteLine("Cancelled by user");
                    else if (combinedCt.Token.IsCancellationRequested)
                        Console.WriteLine("Cancelled by time-out");
                    else 
                        Console.WriteLine("Cancelled by neither user nor time-out");
                }
            }
        }
    }
}

As to your original code, you really did not need ThreadPool.RegisterWaitForSingleObject(l_cts.Token.WaitHandle, ...), there's CancellationToken.Register for that, which returns an IDisposable ready for use with using.

2
  • Thanks @Noseratio, One of the point is about WHEN the Timeout araised. If i'm blocked in a 'long' blocking task i want to know immediatly about the timeout instead has to waiting to detect the cancellation inside the job loop. I'm agree your solution is pretty and precise enought for 90% of use. Thank's again.
    – user996758
    Apr 28, 2014 at 9:36
  • @GuillaumePelletier, if for some reason you can't use cooperative cancellation, you may want to use something like Stephen Toub's WithCancellation for your long-running tasks. You can combine it with CreateLinkedTokenSource if you need to distinguish between the user and time-out cancellation.
    – noseratio
    Apr 28, 2014 at 10:06
1

In order to know if your Task has been cancelled or timed out, you can use the Task.WaitAny overload which takes a TimeSpan:

// Index will return -1 if timeout has occured, otherwise will print the index of the completed task
var cnclToken = new CancellationTokenSource().Token
var yourTask = Task.Run(() => { /* Do stuff */ }, cnclToken);
var index = Task.WhenAny(new[] { yourTask }, TimeSpan.FromSeconds(1));

http://msdn.microsoft.com/en-us/library/dd235645(v=vs.110).aspx

2
  • Thanks for the comment, however, while we can do this using Task.WhenAny{mytask, Task.Delay(ms)} there is NO overload nor extension with time param on WhenAny. your related link is about WaitAny which return an int and NOT awaitable. The WhenAny method result on call to 2 Task which is waste of ressources (i believe, but maybe wrong). Thanks for your time.
    – user996758
    Apr 27, 2014 at 16:45
  • Why is it a waste of resources? WaitAny will wait until either the Task or the TimeSpan will finish, there will only be one task, which is the one running your code. Apr 27, 2014 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.