[英]Handle exception thrown somewhere in a task continuation
What is the best way to handle exceptions thrown somewhere in a task continuation?处理任务继续中某处抛出的异常的最佳方法是什么?
For example, I have a simple task continuation below ( updateMessages
-> updateInterface
) but in reality this could be a chain of more than 2 tasks.例如,我在下面有一个简单的任务延续(
updateMessages
-> updateInterface
),但实际上这可能是一个包含 2 个以上任务的链。 I want to have a generic exception "catch all" task which continues from any fault which could occur in the chain.我想要一个通用异常“捕获所有”任务,该任务从链中可能发生的任何故障继续。
How I'm doing this is by defining an Action
(which observes and logs the exception) and continuing from each task with TaskContinuationOptions.OnlyOnFaulted
set.我的做法是通过定义一个
Action
(它观察并记录异常)并使用TaskContinuationOptions.OnlyOnFaulted
集从每个任务继续。 Is there perhaps a better way of doing this?也许有更好的方法来做到这一点?
Task updateMessages = Task.Factory.StartNew(() =>
{
// Do stuff
});
Task updateInterface = updateMessages.ContinueWith(task =>
{
// UI updates
},
System.Threading.CancellationToken.None,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
Action<Task> failureAction = new Action<Task>(failedTask =>
{
// Observe and log exceptions
});
updateMessages.ContinueWith(failureAction, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
updateInterface.ContinueWith(failureAction, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
Your approach is the approach I use, and it works well.你的方法就是我使用的方法,而且效果很好。
A couple of asides that aren't about the question:一些与问题无关的旁白:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.