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 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why do we use .GetAwaiter.GetResult() instead of .Result?
GetAwaiter().GetResult() avoids an AggregateException wrapper in the case where MethodACore throws an exception.
I was told that calling Async method and awaiting on it to get Sync version is an antipattern and can cause deadlocks.
@SaherAhwal: That is correct. However, this pattern is not blocking on asynchronous code, since the core method is guaranteed to complete synchronously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.