using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CancellationTokenExperiments
{
class CancellationTokenTest
{
static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
tokenSource.Cancel();
Task.Run(() => Console.WriteLine("Hello from Task"), token);
}
}
}
I am trying to understand the concept of cancellationTokens in C#. I understand that the above code will not print "Hello from Task" since the token is checked before the task is run.
However I have a couple of questions.
Task.Run(() => Console.WriteLine("Hello from Task"), token);
What does the above statement mean? In the sense how it is different from simply calling Console.WriteLine("Hello from Task")
? Is it just that we are able to cancel the Task
by passing the token? Also what does the empty braces ()
at the beginning of Task.Run
mean?
- How do I change the above code so that I can stop the execution at a particular instance in time.