Task.Factory.StartNew不会抛出未处理的异常

时间:2015-05-19 20:17:18

标签: c# task-parallel-library

我有以下代码, methodThatThrowsException抛出异常获取静默,我该怎么抛出异常?

TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
CancellationToken token = new CancellationToken();

Task task = Task.Factory.StartNew(MethodThatThrowsException)
                        .ContinueWith(t => { throw t.Exception; }, token, TaskContinuationOptions.OnlyOnFaulted, scheduler)
                        .ContinueWith(w => Vm.StatusMessage.StopProgressBar(), token, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler);

1 个答案:

答案 0 :(得分:1)

您可以通过访问task.Exception属性来接收任务的异常。

   Task task = Task.Factory.StartNew(MethodThatThrowsException)
                    .ContinueWith(t => { throw t.Exception; }, token, TaskContinuationOptions.OnlyOnFaulted, scheduler)
                    .ContinueWith(w => Vm.StatusMessage.StopProgressBar(), token, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler);

   System.Exception yourException = task.Exception;