Using CancellationToken for timeout in Task.Run does not work

Aliostad picture Aliostad · Mar 25, 2014 · Viewed 50.3k times · Source

OK, my questions is really simple. Why this code does not throw TaskCancelledException?

static void Main()
{
    var v = Task.Run(() =>
    {
        Thread.Sleep(1000);
        return 10;
    }, new CancellationTokenSource(500).Token).Result;

    Console.WriteLine(v); // this outputs 10 - instead of throwing error.
    Console.Read();
}

But this one works

static void Main()
{
    var v = Task.Run(() =>
    {
        Thread.Sleep(1000);
        return 10;
    }, new CancellationToken(true).Token).Result;

    Console.WriteLine(v); // this one throws
    Console.Read();
}

Answer

Damien_The_Unbeliever picture Damien_The_Unbeliever · Mar 25, 2014

Cancellation in Managed Threads:

Cancellation is cooperative and is not forced on the listener. The listener determines how to gracefully terminate in response to a cancellation request.

You didn't write any code inside your Task.Run method to access your CancellationToken and to implement cancellation - so you effectively ignored the request for cancellation and ran to completion.