Here is a sample code that creates a new task that simulates a long running process.There is nothing much on the task as such and purely focuses on the cancelling features.I am using cancellation token to cancel the task and the code works fine for me.
CancellationTokenSource CTS= new CancellationTokenSource();
Task<Boolean> PTask = new Task<Boolean>(() =>
{
while (true)
{
if (!CTS.Token.IsCancellationRequested)
{
Thread.Sleep(5000);
}
else{Console.WriteLine("Thread Cancelled");break;}
}
return true;
}, CTS.Token, TaskCreationOptions.None);
PTask.Start();
Console.WriteLine("Hit Enter to cancel the Secondary thread you have started");
Console.ReadLine();
CTS.Cancel();
System.Console.WriteLine(PTask.Result);
}
}
But onething that i could not understand is the token parameter(CTS.Token) that is being passed on to the Task Constructor.What is the actual use of passing the parameter,when i can actually cancel the task even without passing token to the constructor.
Down below is a slightly modified version that works without the token parameter.
CancellationTokenSource CTS= new CancellationTokenSource();
Task<Boolean> PTask = new Task<Boolean>(() =>
{
while (true)
{
if (!CTS.Token.IsCancellationRequested)
{
Thread.Sleep(5000);
}
else
{
Console.WriteLine("Thread Cancelled");
break;
}
};