Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use CancellationTokenSource or CancellationToken to Cancel a task in .NET

I see CancellationToken and CancellationTokenSource both have IsCancellationRequested getter method. Most examples pass CancellationToken to the method that is executed inside the Task. It looks to me by using any of these, call can return. If I use IsCancellationRequested of CancellationTokenSource, will it be a problem? When I should I throw exception (by using ThrowIfCancellationRequested) or just return from the method if there is cancellation request as shown in the following code?

class Program
{
    //If CancellationToken is passed then it behaves in same way?
    public static int TaskMethod(CancellationTokenSource tokenSource)
    {
        int tick = 0;
        while (!tokenSource.IsCancellationRequested)
        {
            Console.Write('*');
            Thread.Sleep(500);
            tick++;
            //token.Token.ThrowIfCancellationRequested();
        }
        //Should I just return or use ThrowIfCancellationRequested?
        return tick;
    }

    public static void Main()
    {
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        CancellationToken token = tokenSource.Token;
        Task<int> task = Task.Factory.StartNew<int>(() => TaskMethod(tokenSource));
        Console.WriteLine("Press enter to stop the task");
        Console.ReadLine();
        tokenSource.Cancel();
        Console.WriteLine("{0}", task.Result);
    }
}
like image 941
RotatingWheel Avatar asked Dec 08 '15 19:12

RotatingWheel


2 Answers

  1. CancellationTokenSource holds and controls CancellationToken instance. The task method is expected to use the cancellation token but not modify it. If you pass CancellationTokenSource to a method, the method gets full control of the cancellation token. So the method should take CancellationToken as a parameter.

  2. The behavior of the method after cancellation request is up to you. There is no rule that the task should be in canceled state (throw TaskCanceledException) if it has been terminated by the cancellation token.

like image 134
Andrey Nasonov Avatar answered Oct 06 '22 00:10

Andrey Nasonov


In my view, CancellationTokenSource is used to start the cancellation (for example, by a another/parent thread, ). CancellationToken.Token is the associated CancellationToken that you would pass to something like TaskFactory.StartNew() as MSDN says:

CancellationTokenSource.IsCancellationRequested property indicates whether cancellation has been requested for this token source, such as due to a call to its Cancel method.

And then the Task would monitor the CancellationToken.IsCancellationRequested to determine when to shut down.

For property CancellationToken.IsCancellationRequested MSDN says:

Gets whether cancellation has been requested for this token.

To sum up, I would like to tell that CancellationTokenSource.IsCancellationRequested is used to associate CancellationToken with TaskFactory.StartNew(). And CancellationToken.IsCancellationRequested is used to define whether cancellation has been requested for this token. Moreover, IntelliSense has the same definition for CancellationTokenSource.Token.IsCancellationRequested and for CancellationToken.IsCancellationRequested.

like image 29
StepUp Avatar answered Oct 05 '22 23:10

StepUp