gpt4 book ai didi

c# - 何时隐式调用 `Dispose`来重构: using statement without scope,?

转载 作者:行者123 更新时间:2023-12-03 13:50:45 24 4
gpt4 key购买 nike

前几天我在进行重构,遇到了类似这样的事情:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com