如何使用ContinueWith在任务中正确管理异常 [英] How to manage properly an exception in a Task with ContinueWith
问题描述
阅读有关任务和exepcion管理的信息后,我将使用以下代码来管理Task中引发的异常:
After reading information about task and exepcion management, I am using this code to manage an exception thrown in a Task:
Task<Object> myTask = Task.Factory.StartNew<Object>(doTask, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
myTask .ContinueWith(task => afterTask(task), TaskScheduler.FromCurrentSynchronizationContext());
doTask和AfterTask在哪里:
Where doTask and AfterTask are:
private <Object> doTask() {
throw new Exception("BOOM");
}
private afterTask(Task<Object> aTask) {
if (aTask.IsFaulted)
{
MessageBox.Show(aTask.Exception.InnerException.Message);
}
else //whatever
}
引发异常繁荣时,Visual Studio将显示警报,通知尚未捕获到异常,但是如果我继续执行该异常,则将在afterTask函数中进行处理.
When Exception Boom is thrown the Visual Studio shows an alert informing that an exception has not been caught but if I continue executing the exception is processed in the afterTask function.
此代码正确吗?还是我误解了该任务的一些基本行为?有什么方法可以避免调试器发出警报,提示尚未捕获执行?有点烦人...
Is this code correct or I missunderstood some basic behaviour of the task? There is any way to avoid the alert from the debugger that the execption has not been caught? Is a bit annoying...
预先感谢
推荐答案
尝试以下方法:
task.ContinueWith(
t =>
t.Exception.Handle(ex =>
{
logger.Error(ex.Message, ex);
return false;
})
, TaskContinuationOptions.OnlyOnFaulted
);
使用TaskContinuationOptions.OnlyOnFaulted
,仅当原始任务抛出异常时,才运行ContinueWith
块.
By using the TaskContinuationOptions.OnlyOnFaulted
, you run your ContinueWith
block only if an exception is thrown by the original task.
另外,您可以从传递给Handle
的lambda中选择是返回true还是false,以指示是否已处理异常.就我而言,我不想阻止该异常的传播.您可能需要更改它,以根据情况返回true
.
Aditionally, you can choose whether to return true or false from the lambda passed to Handle
, indicating whether the exception has been handled or not. In my case, I didn't want to stop the exception from propagating. You might want to change it to return true
in your case.
这篇关于如何使用ContinueWith在任务中正确管理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!