前几天我在重构代码时,遇到了这样的情况:
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."));
}
}
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."));
}
我有点怀疑,实际上我不确定第二个版本中隐式Dispose
调用会在什么时候发生。
我该如何知道呢?
using var scope = ...;
的意思是在离开Handle
作用域时,scope
将被Disposed
。 - Dmitry Bychenkopublic class TestDispose : IDisposable { public void Dispose(){ Console.WriteLine("disposing"); }}
来测试它何时被调用。 - germi