【发布时间】:2015-12-09 05:00:38
【问题描述】:
我看到CancellationToken 和CancellationTokenSource 都有IsCancellationRequested getter 方法。大多数示例将CancellationToken 传递给在Task 内部执行的方法。在我看来,使用其中任何一个,调用都可以返回。如果我使用IsCancellationRequested 的CancellationTokenSource,会不会有问题?我应该在什么时候抛出异常(通过使用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);
}
}
【问题讨论】:
-
仅当您希望它执行取消时才将方法传递给
CancellationTokenSource。如果该方法是被取消的东西,请将其传递给CancellationToken。
标签: c# task-parallel-library task