如何获取以任务 <int> 格式返回的整数值 - Asp.net Core MVC - MediaTr

How to get the integer value returned in Task <int> format - Asp.net Core MVC - MediaTr

将记录保存到数据库后,我需要获取将从我的域层返回的 Id。为此,我使用了 MediaTr 库的功能。

public class PessoaCommandHandler : CommandHandler,
    IRequestHandler<RegisterNewPessoaCommand, int>,
    IRequestHandler<UpdatePessoaCommand, int>,
    IRequestHandler<RemovePessoaCommand, int>
{
    private readonly IPessoaRepository _pessoaRepository;
    private bool _allowEndTransaction;
    private readonly IMediatorHandler Bus;

    public PessoaCommandHandler(IPessoaRepository pessoaRepository,
                                  IUnitOfWork uow,
                                  IMediatorHandler bus,
                                  INotificationHandler<DomainNotification> notifications) : base(uow, bus, notifications)
    {
        _pessoaRepository = pessoaRepository;
        _allowEndTransaction = true;
        Bus = bus;
    }

    public Task<int> Handle(RegisterNewPessoaCommand message, CancellationToken cancellationToken)
    {
        if (!message.IsValid())
        {
            NotifyValidationErrors(message);
            return Task.FromResult(0);
        }

         var pessoaModel = new Pessoa(message.PessoaNatureza);
         _pessoaRepository.Add(pessoaModel);

        return Task.FromResult(pessoaModel.Id);

    }
}

现在,让我们开始讨论问题: 我需要获取 "Result" 属性 中的整数值并将其放入 personId 变量中,但我不知道该怎么做。有人知道怎么做吗?

public void Register(PessoaViewModel pessoaViewModel)
{
    var registerCommand = _mapper.Map<RegisterNewPessoaCommand>(pessoaViewModel);
    var pessoaId = Bus.SendCommand(registerCommand);
}

解开由 Task 编辑的值 return 的最简单方法可能是使用 async/await.

不过,您会希望尽可能避开 async void 方法,因为这会导致无法等待 "fire and forget" 方法(这可能会变成调试噩梦,因为任何异常将丢失到 void 等)——所以让我们使用 Register 方法 return a Task 代替:

async public Task Register(PessoaViewModel pessoaViewModel)
{
    var registerCommand = _mapper.Map<RegisterNewPessoaCommand>(pessoaViewModel);
    var pessoaId = await Bus.SendCommand(registerCommand);

    // use `pessoaId` as needed
}

如果由于某种原因 async/await 不可用,也可以使用以下选项(但请注意,此选项是同步的,会阻塞当前线程执行等):

public void Register(PessoaViewModel pessoaViewModel)
{
    var registerCommand = _mapper.Map<RegisterNewPessoaCommand>(pessoaViewModel);
    var pessoaId = Bus.SendCommand(registerCommand).GetAwaiter().GetResult();

    // use `pessoaId` as needed
}

为了完整起见,我要补充一点,也可以使用 Bus.SendCommand(registerCommand).Result; 但这通常被认为是不好的做法,因为它会混淆聚合异常等内部的任何异常。

此外,here's 对关于展开如何发生的类似问题的可靠回答。