我有一个使用取消令牌的后台长时间运行方法。取消时,即使调用了 CancellationTokensource.Token.Register 上的方法,线程仍然继续处理。
有没有办法在调用 register 后停止处理线程?
CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
void HandleBackgroundTasks(object args)
{
var task = Task.Factory.StartNew(() => BackgroundTask(),
_cancellationTokensource.Token);
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
//handle faulted
}
}
}
void BackgroundTask()
{
_cancellationTokenSource.Token.Register(() =>
{
service.CancelTask();//method to reset database values on cancel
}
//Some code to check whether to run HandleLongrunningTask method
service.HandleLongrunningTask(); //long running task
}
答案 0 :(得分:1)
CancellationToken 不会强制停止处理。
执行处理的代码需要使用 CancellationToken,方法是将其传递给其他函数或调用 ThrowIfCancellationRequested(或检查 IsCancellationRequested),并让结果 OperationCanceledException 展开堆栈。