I see CancellationToken and CancellationTokenSource both have IsCancellationRequested getter method. Most examples pass CancellationToken to the method that is executed inside the Task. It looks to me by using any of these, call can return. If I use IsCancellationRequested of CancellationTokenSource, will it be a problem? When I should I throw exception (by using ThrowIfCancellationRequested) or just return from the method if there is cancellation request as shown in the following code?
class Program
{
//If CancellationToken is passed then it behaves in same way?
public static int TaskMethod(CancellationTokenSource tokenSource)
{
int tick = 0;
while (!tokenSource.IsCancellationRequested)
{
Console.Write('*');
Thread.Sleep(500);
tick++;
//token.Token.ThrowIfCancellationRequested();
}
//Should I just return or use ThrowIfCancellationRequested?
return tick;
}
public static void Main()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task<int> task = Task.Factory.StartNew<int>(() => TaskMethod(tokenSource));
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
tokenSource.Cancel();
Console.WriteLine("{0}", task.Result);
}
}