继续取消任务

时间:2013-10-10 12:56:45

标签: c# task-parallel-library

我试图在取消后设置延续任务。但我无法在内部处理异常。

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块包装代码,我会收到一条错误说"对象实例没有设置为对象的引用"。

有什么想法吗?

0 个答案:

没有答案