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);
}
}
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With