0

I'm developing an web API using CQRS pattern. I have a command to Create Author.

Here is my Command Handler:

internal sealed class AddCommandHandler : ICommandHandler<CreateAuthorCommand, Author>
{
    private readonly IUnitOfWork _unitOfWork;

    public AddCommandHandler(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
    }

    public async Task<Result<Author>> Handle(CreateAuthorCommand command)
    {
        var nameResult = Name.Create(command.FirstName, command.LastName);
        var birthDateResult = BirthDate.Create(command.DateOfBirth);
        var mainCategoryResult = Entities.Authors.MainCategory.Create(command.MainCategory);

        var authorResult = Result.Combine(nameResult, birthDateResult, mainCategoryResult)
                            .Map(() => new Author(nameResult.Value, birthDateResult.Value, null, mainCategoryResult.Value));

        if (authorResult.IsFailure)
            return Result.Failure<Author>(authorResult.Error);

        await _unitOfWork.AuthorRepository.AddAsync(authorResult.Value);

        await _unitOfWork.SaveChangesAsync();

        return Result.Success(authorResult.Value);
    }
}

I have Microsoft.CodeAnalysis.FxCopAnalyzers and Roslynator.Analyzers nuget packages installed in my project. These packages shows the following Warning and Message for await _unitOfWork.AuthorRepository.AddAsync(authorResult.Value) and await _unitOfWork.SaveChangesAsync().

CA2007 Consider Calling ConfigureAwait on the awaited task

RCS1090 Call 'ConfigureAwait(false).'

There are lots of questions posted on this .ConfigureAwait

But can anyone explain me in layman terms on why I should do this? Adding .ConfigureAwait(false) removed the warning and message. But I need to understand this clearly on when to .ConfigureAwait(true) and when to .ConfigureAwait(false). Please assist and teach me.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
fingers10
  • 6,675
  • 10
  • 49
  • 87
  • 2
    [This blog post](https://devblogs.microsoft.com/dotnet/configureawait-faq/#why-would-i-want-to-use-configureawaitfalse) explains it quite well – Simply Ged Aug 16 '20 at 01:36
  • My question is since this is an API project I don't need to worry on synchronization context and I can always chain `.ConfigureAwait(false)` to my `await` calls? – fingers10 Aug 16 '20 at 02:19
  • 1
    If your API does not accept delegates from the caller, then yes, do use `ConfigureAwait(false)` everywhere in your library. If it does accept delegates then invoking them outside of a sync context could be an issue. You can see [here](https://github.com/App-vNext/Polly/wiki/Asynchronous-action-execution#synchronizationcontext) how the Polly library dealt with this dilemma. – Theodor Zoulias Aug 16 '20 at 03:16

0 Answers0