重构:使用没有作用域的语句,隐式`Dispose` 调用何时发生?

Eho*_*ret 6 c# dispose using-statement .net-core

前几天我正在重构一些东西,我遇到了这样的事情:

public async Task<Result> Handle(CancelInitiatedCashoutCommand command, CancellationToken cancellationToken)
{
    using (_logger.BeginScope("{@CancelCashoutCommand}", command))
    {
        return await GetCashoutAsync(command.CashoutId)
            .Bind(IsStatePending)
            .Tap(SetCancelledStateAsync)
            .Tap(_ => _logger.LogInformation("Cashout cancellation succeeded."));
    }
}
Run Code Online (Sandbox Code Playgroud)

ReSharper 建议将其重构为:

public async Task<Result> Handle(CancelInitiatedCashoutCommand command, CancellationToken cancellationToken)
{
    using var scope = _logger.BeginScope("{@CancelCashoutCommand}", command);
    return await GetCashoutAsync(command.CashoutId)
        .Bind(IsStatePending)
        .Tap(SetCancelledStateAsync)
        .Tap(_ => _logger.LogInformation("Cashout cancellation succeeded."));
}
Run Code Online (Sandbox Code Playgroud)

我有点怀疑,实际上我不确定Dispose第二个版本何时会发生隐式调用。

我怎么知道?

Dmi*_*nko 5

Resharper 建议使用声明功能的C# 8.0

 public async Task<Result> Handle(CancelInitiatedCashoutCommand command, 
                                  CancellationToken cancellationToken)
 {  
    using var scope = ...;
    ...
 } // <- scope will be Disposed on leaving its scope (here on Handle method's scope)
Run Code Online (Sandbox Code Playgroud)