Here is a sample code that creates a new task that simulates a long running process. There is nothing much on the task as such and purely focuses on the cancelling features. I am using cancellation token to cancel the task and the code works fine for me.
CancellationTokenSource CTS = new CancellationTokenSource();
Task<Boolean> PTask = new Task<Boolean>(() =>
{
while (true)
{
if (!CTS.Token.IsCancellationRequested)
{
Thread.Sleep(5000);
}
else { Console.WriteLine("Thread Cancelled");break; }
}
return true;
}, CTS.Token, TaskCreationOptions.None);
PTask.Start();
Console.WriteLine("Hit Enter to cancel the Secondary thread you have started");
Console.ReadLine();
CTS.Cancel();
System.Console.WriteLine(PTask.Result);
But one thing that I could not understand is the token parameter (CTS.Token
) that is being passed on to the Task
constructor. What is the actual use of passing the parameter, when I can actually cancel the task even without passing token to the constructor.
Down below is a slightly modified version that works without the token parameter.
CancellationTokenSource CTS = new CancellationTokenSource();
Task<Boolean> PTask = new Task<Boolean>(() =>
{
while (true)
{
if (!CTS.Token.IsCancellationRequested)
{
Thread.Sleep(5000);
}
else
{
Console.WriteLine("Thread Cancelled");
break;
}
};
A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.
The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself. In the above case, the operation will just end when cancellation is requested via Cancel() method.
So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp. NetCore MVC application.
Using CancellationToken to Cancel Requests Sent with HttpClient. In the introduction, we stated that if a user navigates away from a page, they need the response no more, and thus it is a good practice to cancel that request. But there is more than that.
UPDATE: The following msdn question describes the reason:
Passing a token into StartNew associates the token with the Task. This has two primary benefits:
If the token has cancellation requested prior to the Task starting to execute, the Task won't execute. Rather than transitioning to Running, it'll immediately transition to Canceled. This avoids the costs of running the task if it would just be canceled while running anyway.
If the body of the task is also monitoring the cancellation token and throws an OperationCanceledException containing that token (which is what
ThrowIfCancellationRequested
does), then when the task sees that OCE, it checks whether the OCE's token matches the Task's token. If it does, that exception is viewed as an acknowledgement of cooperative cancellation and the Task transitions to the Canceled state (rather than the Faulted state).
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