【发布时间】:2013-10-24 02:34:36
【问题描述】:
我正在研究Exam Ref 70-483: Programming in C# 书中的示例,并遇到了清单 1-44 中的以下代码的问题。在这个例子中,作者试图证明一个延续任务可以访问在前面的任务中抛出的未处理的异常,并且可以在适当的时候处理它们。
static void Main(string[] args)
{
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 canceled 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();
}
不幸的是,这行代码在继续
t.Exception.Handle((e) => true);
抛出异常,因为 t.Exception 是 null。
在该行设置断点,我可以看到t.Status 是Canceled,而不是Faulted。这就是为什么异常不可用的原因吗?处理前面任务中抛出的异常的正确方法是什么?
【问题讨论】: