前几天我在进行重构,遇到了类似这样的事情:
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
调用。我怎么知道?
最佳答案
Resharper建议使用 C#8.0 using declaration功能:
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)
关于c# - 何时隐式调用 `Dispose`来重构: using statement without scope,?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59285021/