同步方法调用内部带有异步方法的异步方法

时间:2020-08-31 12:06:47

标签: asynchronous

我想为每个方法创建“同步”和“异步”,但无需复制代码。如果我在内部调用了Async方法和其他Async方法,这是正确的代码吗?。

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

1 个答案:

答案 0 :(得分:3)

Synchronous wrappers for asynchronous methods is an antipattern。首先,我建议您仅支持异步API。但这有时是不可能的,例如,出于向后兼容的原因。

在这种情况下,我建议使用boolean argument 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);
}