I want to understand how the CancellationToken works, and how it cancels tasks.
For that, I created this example, which uses the same token for both the Task.Run() and the inner method - HelpDoingSomething()
So, I let the task run for 500ms, then I cancel the token, and the result is:
First printed message: "HelpDoingSomething cancelled" and then "DoSomething cancelled"
class Program
{
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
var myClass = new MyClass(cts.Token);
myClass.DoSomething();
Thread.Sleep(500);
cts.Cancel();
System.Console.ReadKey();
}
}
internal class MyClass
{
private CancellationToken token;
public MyClass(CancellationToken token)
{
this.token = token;
}
public void DoSomething()
{
Task.Run(() =>
{
HelpDoingSomething();
System.Console.WriteLine("DoSomething cancelled");
}, token);
}
private void HelpDoingSomething()
{
while (!token.IsCancellationRequested)
{
//Keep doing something
System.Console.Write(".");
}
System.Console.WriteLine("HelpDoingSomething cancelled");
}
}
I know exactly that my method HelpDoingSomething() checks if the cancellationToken was requested on each iteration of the loop.
My question is how and how often does the Task.Run() method check if a cancellation token is requested?
Is that possible that Task.Run() will check that before HelpDoingSomething() does, and I will see only one message printed ("DoSomething cancelled")? This means the logic may not be handled correctly in this method.
CodePudding user response:
