我正在尝试在取消后设置继续任务。但我无法在内部处理异常。
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
Console.Write("*");
Thread.Sleep(1000);
}
throw new OperationCanceledException();
}, token).ContinueWith((t) =>
{
t.Exception.Handle((e) => true);
Console.WriteLine("You have cancelled the task");
}, TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
Console.WriteLine("Press enter to end the application");
Console.ReadLine();
代码不处理异常。如果我用 try 块包装代码,我会收到一条错误消息“对象实例未设置为对象的引用”。
任何想法?