我正在开发一个系统,在该系统中,期望多个客户端对象通过接口实现特定功能,并且我希望该功能与延续异步运行(我希望实现是 I/O 绑定的并且想要确保所有客户端对象尽快完成此功能)。我正在使用 Visual Studio Async CTP Refresh for SP1,使用 C#“5.0”。
在我的抽象类的子对象中强制执行异步行为的推荐做法是什么(见下文)?我不能(显然)使用虚拟方法方法强制使用“异步”方法。我只能要求一个“任务”返回类型。这是否意味着我不应该尝试在子对象中要求异步行为?在那种情况下,返回类型是否应该只是“void”?
公共接口是目前系统设计的一个不幸结果,但这是一个单独的问题。显然,我不能限制任何绕过“BaseFoo”并只实现“IFoo”接口的异步。
这是代码:
public interface IFoo
{
void Bar(); //NOTE: Cannot use 'async' on methods without bodies.
}
public abstract class BaseFoo : IFoo
{
public async void Bar()
{
await OnBar(); //QUESTION: What is the right "async delegation" pattern?
}
protected virtual async Task OnBar()
{
await TaskEx.Yield();
}
}
public class RealFoo : BaseFoo //NOTE: May be implemented by 3rd party
{
protected override async Task OnBar()
{
//CLIENT: Do work, potentially awaiting async calls
await TaskEx.Yield(); //SECONDARY QUESTION: Is there a way to avoid this if there are no 'awaits' in the client's work?
}
}