0

For each Method i want create Sync and Async, But without duplicating the code. I f I call an Async Method with other Async Methods inside, is it a correct code?.

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 Answers1

4

Synchronous wrappers for asynchronous methods is an antipattern. First, I recommend that you only support an asynchronous API. But sometimes this isn't possible, e.g., for backwards compatibility reasons.

In that case, I recommend the boolean argument hack, which looks something like this:

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);
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810