I am trying learn how to cancel Task using cancellation token. Here, I have written a UnitTest for it but i am not getting the way it is working.
[TestMethod]
public async Task Task_should_not_run_when_token_cancelled_before_its_call()
{
var cts = new CancellationTokenSource();
var token = cts.Token;
cts.Cancel();
Debug.WriteLine("Calling Cancellable Method".ToUpper());
try
{
await CheckMeCalled(token);
}
catch (Exception expException)
{
}
}
private async Task CheckMeCalled(CancellationToken ct)
{
Debug.WriteLine("Before task delayed".ToUpper());
await Task.Delay(5000);
Debug.WriteLine("After task delayed".ToUpper());
}
In the above Test i Called the cts.Cancel()
before calling the CheckMeCalled
method. so it should not run as it canceled. But it is running to the full extent.
I have read somewhere that
If Task is not running and you cancel it then it will not go to a running state instead it go for canceled state when you call it
.
But it is not seems to be happening here. can somebody explain it to me ? any help is appreciated. cheers :)
You have to manually check the token to see if a cancellation was requested.
With:
The quote you added was related to creating a new
Task
viaTask.Run
orTask.Factory.Startnew
. When passing aCancellationToken
to your method, you have to actively check the token before runningHere is a quote by Stephan Toub regarding cancellation token and
Task
:I also recommend reading NET 4 Cancellation Framework for a broad review of the cancellation mechanism by the PFX Team