I made a task to count the number, the task will receive the cancel request after 5 seconds, however after the task is cancelled I checked the status of task. The status of task is still running. Why? The sample code is below:
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);//Request Cancel after 5 seconds
var newTask = Task.Factory.StartNew(state =>
{
try
{
int i = 1;
var token = (System.Threading.CancellationToken)state;
while (true)
{
Console.WriteLine(i);
i++;
Thread.Sleep(1000);
token.ThrowIfCancellationRequested();
}
}
catch
{
}
finally
{
}
}, cts.Token, cts.Token);
try
{
newTask.Wait(10000, cts.Token);
}
catch
{
Console.WriteLine("Catch:"+ newTask.Status);//The status is Running
}
Console.ReadLine();