我看到CancellationToken
和CancellationTokenSource
都有IsCancellationRequested
getter方法。大多数示例将CancellationToken
传递给在Task
内执行的方法。它通过使用任何这些看起来对我来说,电话可以返回。如果我使用CancellationTokenSource
的IsCancellationRequested
,会不会成为问题?当我应该抛出异常(通过使用ThrowIfCancellationRequested
)或者只是从方法返回时,如果有取消请求,如下面的代码所示?我应该使用CancellationTokenSource还是CancellationToken取消.NET中的任务
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);
}
}
请仔细阅读http://stackoverflow.com/questions/14215784/why-cancellationtoken-is-separate-from-cancellationtokensource –
传递的方法'CancellationTokenSource'只有当你想要它做的取消。如果该方法被取消,则将其传递给CancellationToken。 –