考虑在等待的任务上调用ConfigureAwait

时间:2020-08-16 01:27:32

标签: c# async-await synchronizationcontext configureawait

我正在使用CQRS模式开发Web API。我有一个创建作者的命令。

这是我的命令处理程序:

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);
    }
}

我的项目中安装了Microsoft.CodeAnalysis.FxCopAnalyzersRoslynator.Analyzers nuget软件包。这些软件包为await _unitOfWork.AuthorRepository.AddAsync(authorResult.Value)await _unitOfWork.SaveChangesAsync()显示以下警告和消息。

CA2007考虑​​在等待的任务上调用ConfigureAwait

RCS1090调用“ ConfigureAwait(false)。”

.ConfigureAwait

上有很多问题

但是有人可以用外行的方式向我解释为什么我应该这样做吗?添加.ConfigureAwait(false)删除了警告和消息。但是我需要在何时.ConfigureAwait(true)和何时.ConfigureAwait(false)上清楚地了解这一点。请协助教我。

0 个答案:

没有答案
相关问题