使用任务延续时如何避免过度嵌套异常
How to avoid over-nesting exceptions when using Task continuations
在我的代码的某些部分,我有这个:
task.Exception.InnerException.InnerException.Message
这对我来说似乎是错误的。正常吗?
这个问题的起源是当我对任务执行 ContinueWith 时,但在 ContinueWith 中,如果不是成功案例,则再次抛出异常,如下所示:
t.ContinueWith(task =>
{
if (task.Exception != null) throw task.Exception;
// do something with task.Result
});
我尝试仅在 TaskContinuationOptions.OnlyOnRanToCompletion
情况下继续执行,但随后未传播异常并且任务被视为已取消而不是出现故障。
最简单的方法就是简单地使用 async/await 习语。
try
{
await SomeTask();
await SomeOtherTask();
SomeSynchronousProcessing();
}
catch(Exception ex)
{
}
这与链接一系列任务相同,如果一个任务失败,其他任务将被跳过。
在我的代码的某些部分,我有这个:
task.Exception.InnerException.InnerException.Message
这对我来说似乎是错误的。正常吗?
这个问题的起源是当我对任务执行 ContinueWith 时,但在 ContinueWith 中,如果不是成功案例,则再次抛出异常,如下所示:
t.ContinueWith(task =>
{
if (task.Exception != null) throw task.Exception;
// do something with task.Result
});
我尝试仅在 TaskContinuationOptions.OnlyOnRanToCompletion
情况下继续执行,但随后未传播异常并且任务被视为已取消而不是出现故障。
最简单的方法就是简单地使用 async/await 习语。
try
{
await SomeTask();
await SomeOtherTask();
SomeSynchronousProcessing();
}
catch(Exception ex)
{
}
这与链接一系列任务相同,如果一个任务失败,其他任务将被跳过。