首页 > 解决方案 > 基础设施 - 同步和异步接口和实现?

问题描述

当实现一个库/基础设施时,这个 API 的用户想要同步和异步地使用代码,我读到混合同步和异步不是一个好主意(例如同步实现包括等待异步实现)。

所以显然同步和异步实现应该分开。

是否有一种优雅的方法可以避免同步和异步实现的代码(或更准确地说是“流”)重复,这显然会冒泡到整个调用层次结构?

interface IMyInterface 
{
    void Foo();
    Task FooAsync();
}

class MyImplementation1 : IMyInterface
{
    public void Foo()
    {
        OtherMethod1();
        OtherMethod2();
        OtherMethod3();
        OtherMethod4();
    }

    public async Task FooAsync()
    {
        await OtherMethod1Async();
        await OtherMethod2Async();
        await OtherMethod3Async();
        await OtherMethod4Async();
    }

    private void OtherMethod1() { /* may contain other sync calls */ }
    private void OtherMethod2() { /* may contain other sync calls */ }
    private void OtherMethod3() { /* may contain other sync calls */ }
    private void OtherMethod4() { /* may contain other sync calls */ }  

    private async Task OtherMethod1Async() { /* may contain other async calls */ }
    private async Task OtherMethod2Async() { /* may contain other async calls */ }
    private async Task OtherMethod3Async() { /* may contain other async calls */ }
    private async Task OtherMethod4Async() { /* may contain other async calls */ }      
}

标签: c#asynchronousasync-awaitcode-duplication

解决方案


根据您的逻辑,您仍然可以共享一些逻辑。但在不同的地方,它应该不同。

如果有帮助,您可以使用模板系统(如T4)生成代码。


推荐阅读