首页 > 解决方案 > 同步方法调用异步方法,里面有异步方法

问题描述

对于我想要创建同步和异步的每个方法,但不复制代码。如果我在内部调用带有其他异步方法的异步方法,它是正确的代码吗?

public void MethodA(){//1
    MethodAAsync().GetAwaiter();        
}

public void MethodA(){//2 is it a correct code
    MethodB();
    MethodC();
    ...code
    ...code
    ...code
    MethodD();
    MethodE();  
}

public async Task MethodAAsync(){
    await MethodBAsync(cancellationToken);
    await MethodCAsync(cancellationToken);
    ...code
    ...code
    ...code
    await MethodDAsync(cancellationToken);
    await MethodEAsync(cancellationToken);
}

//1 or 2

标签: asynchronous

解决方案


异步方法的同步包装器是一种反模式。首先,我建议您只支持异步 API。但有时这是不可能的,例如,出于向后兼容性的原因。

在这种情况下,我建议使用布尔参数 hack,它看起来像这样:

public void MethodA() {
  MethodACore(sync: true).GetAwaiter().GetResult();
}

public Task MethodAAsync() {
  return MethodACore(sync: false);
}

private async Task MethodACore(bool sync) {
  if (sync) MethodB(); else await MethodBAsync(cancellationToken);
  if (sync) MethodC(); else await MethodCAsync(cancellationToken);
  ...code
  ...code
  ...code
  if (sync) MethodD(); else await MethodDAsync(cancellationToken);
  if (sync) MethodE(); else await MethodEAsync(cancellationToken);
}

推荐阅读