我看到 CancellationToken
和 CancellationTokenSource
都有 IsCancellationRequested
获取方法。大多数示例将 CancellationToken
传递给在 Task
中执行的方法。在我的理解中,使用其中任何一个,调用都可以返回。如果我使用 CancellationTokenSource
的 IsCancellationRequested
,会有问题吗?何时应该抛出异常(使用 ThrowIfCancellationRequested
),或者当有取消请求时只是从方法中返回,就像下面的代码一样?
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);
}
}