【问题标题】:Task.Factory.StartNew doesn't throw unhandled exceptionTask.Factory.StartNew 不会抛出未处理的异常
【发布时间】:2015-05-20 04:25:06
【问题描述】:

我有下面的代码,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);

【问题讨论】:

标签: c# task-parallel-library


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多