What is the use of CancellationToken
's IsCancellationRequested
property? Consider below code
static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
Console.WriteLine("Press Enter to Start.\nAgain Press enter to finish.");
Console.ReadLine();
Task t = new Task(() =>
{
int i = 0;
while (true)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Task Cancel requested");
break;
}
Console.WriteLine(i++);
}
}, token);
t.Start();
// wait for input before exiting
Console.ReadLine();
tokenSource.Cancel();
if(t.Status==TaskStatus.Canceled)
Console.WriteLine("Task was cancelled");
else
Console.WriteLine("Task completed");
}
I find that on rare occasions code inside if
block doesn't run. If so what is the use of polling to see if cancellation is requested?