【发布时间】:2016-08-05 01:25:32
【问题描述】:
我有以下场景:
组件A提供接口IMyInterface和注册机制,供其他组件注册其实现者。
界面如下:
public interface IMyInterface
{
Task DoSomethingAsync(Context context);
}
在组件 A 中,我想为所有实现者“并行”启动方法,然后等待任务。 实现者可能会在他们的实现中抛出异常(在我的具体场景中,涉及到 IO,我希望不时发生 IOExceptions;组件 A 确保正确捕获异常......)。
代码如下所示
var tasks = new List<Task>();
foreach (var impl in implementors)
{
var context = ...;
tasks.Add(impl.DoSomethingAsync(context));
}
// now do something different that takes some time
try
{
await Task.WhenAll(tasks);
}
catch(Exception e)
{
// swallow. we handle the exceptions for each task below.
}
foreach (var task in tasks)
{
if (task.IsFaulted)
// log, recover, etc...
}
所以这是我的问题:
由于我不将await 用于单个任务,因此异常行为取决于实现者“创建”返回的Task 的方式。
public class Implementor1 : IMyInterface
{
public async Task DoSomethingAsync(Context context)
{
// no awaits used in code here!
throw new Exception("oh the humanity");
}
}
public class Implementor2 : IMyInterface
{
public Task DoSomethingAsync(Context context)
{
throw new Exception("oh the humanity");
return Task.CompletedTask;
}
}
(注意区别:第一个实现者使用了async 关键字。)
在实现者 1 上调用 DoSomethingAsync 时,组件 A 中没有引发异常。任务对象设置为“故障”,我可以从任务中检索异常。 -> 正如我所料。
在实现者 2 上调用 DoSomethingAsync 时,立即抛出异常。 -> 不是我想要的。
问题来了: 如何处理这种情况以始终观察行为 1?我无法控制其他组件的作者如何实现我的界面。
【问题讨论】:
标签: c# asynchronous exception-handling