17

Obviously I realize it enables me to cancel the task, but this code achieves the same effect without having to pass the token into Task.Run

What is the practical difference? Thanks.

Dim cts As New CancellationTokenSource
Dim ct As CancellationToken = cts.Token
Task.Run(Sub()
             For i = 1 To 1000
                 Debug.WriteLine(i)
                 ct.ThrowIfCancellationRequested()
                 Threading.Thread.Sleep(10)
             Next
         End Sub)

cts.CancelAfter(500)

VS

Dim cts As New CancellationTokenSource
Dim ct As CancellationToken = cts.Token
Task.Run(Sub()
             For i = 1 To 1000
                 Debug.WriteLine(i)
                 ct.ThrowIfCancellationRequested()
                 Threading.Thread.Sleep(10)
             Next
         End Sub, ct)

cts.CancelAfter(500)
JohnWick
  • 4,929
  • 9
  • 37
  • 74
  • 1
    In that case it wouldn't make much difference but it's quite possible that the context of the `Task` doesn't have access to the original variable that the token was assigned to. For instance, if object A created a `Task` that executed a method of object B, B may not have any knowledge of the existence of A so how could it access a `CancellationToken` assigned only to a local variable within A? – jmcilhinney Jan 18 '18 at 03:15
  • @jmcilhinney Great point, was thinking the same thing. Much more versatile in a non-trivial use case. You answer alot of my questions by the way, I really appreciate your help jmcilhinney – JohnWick Jan 18 '18 at 04:10

2 Answers2

21

The API docs for Task.Run(Action, CancellationToken) has this remark:

If cancellation is requested before the task begins execution, the task does not execute. Instead it is set to the Canceled state and throws a TaskCanceledException exception.

So in your scenario, there isn't any practical difference because you wait 500 milliseconds before issuing the cancellation. In that time the task is scheduled, begins execution, and runs through the loop a number of times before the cancellation is issued, manifesting as an exception thrown from ct.ThrowIfCancellationRequested().

The difference between Task.Run(Action) and Task.Run(Action, CancellationToken) is more apparent with this modified version of your example:

Try
    Dim cts As New CancellationTokenSource
    Dim ct As CancellationToken = cts.Token

    cts.Cancel()

    Dim task As Task = Task.Run(
        Sub()
            Console.WriteLine("Started running your code!")
            ct.ThrowIfCancellationRequested()
            Console.WriteLine("Finished running your code!")
        End Sub, ct)

    task.Wait()

Catch ex As AggregateException
    Console.Error.WriteLine("Caught exception: " & ex.InnerException.Message)
End Try

Console.WriteLine("Done, press Enter to quit.")
Console.ReadLine()

In this scenario, Task.Run schedules the task to run, but also associates the cancellation token with that task. When we call task.Wait(), before the thread pool executes the task, it checks the cancellation token and notices that a cancellation has been issued on that token, so it decides to cancel before executing the task. So the output is:

Caught exception: A task was canceled.
Done, press Enter to quit.

If you instead replace: End Sub, ct) with End Sub), then the thread pool isn't aware of the cancellation token, so even though you've issued a cancellation, it proceeds with executing the task, before your task code itself checks for cancellation. So the output is:

Started running your code!
Caught exception: The operation was canceled.
Done, press Enter to quit.

(You can see that the exception message is slightly different in these two cases as well.)

In summary, providing the cancellation token to the Task.Run method allows the thread pool itself to know if the task is cancelled before the thread pool gets a chance to execute the task. This allows the thread pool to save time and resources by not even bothering to start running the task.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34
1

The practical difference is what state the Task will be in if the token is canceled.

Sorry about the C# code here...

var cts = new CancellationTokenSource();
var withToken = Task.Run(Callback, cts.Token);
var withoutToken = Task.Run(Callback);
cts.Cancel();
void Callback()
{
    Thread.Sleep(1000);
    throw new OperationCanceledException(cts.Token);
}

try
{
    Task.WaitAll(withToken, withoutToken);
}
catch
{
}

Console.WriteLine($"withToken.IsCanceled:    {withToken.IsCanceled}");
Console.WriteLine($"withToken.IsFaulted:     {withToken.IsFaulted}");
Console.WriteLine($"withToken.Status:        {withToken.Status}");
Console.WriteLine();
Console.WriteLine($"withoutToken.IsCanceled: {withoutToken.IsCanceled}");
Console.WriteLine($"withoutToken.IsFaulted:  {withoutToken.IsFaulted}");
Console.WriteLine($"withoutToken.Status:     {withoutToken.Status}");

That code prints:

withToken.IsCanceled:    True
withToken.IsFaulted:     False
withToken.Status:        Canceled

withoutToken.IsCanceled: False
withoutToken.IsFaulted:  True
withoutToken.Status:     Faulted

The idea here is that if an OperationCanceledException (or a derived type) gets thrown by the callback that you pass to Task.Run, then the resulting Task will get marked as "Faulted" unless the exception's CancellationToken is equal to the token that you passed in (and that CancellationToken is canceled at the time you throw the exception).

Joe Amenta
  • 4,662
  • 2
  • 29
  • 38