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

标签 c# .net-core dispose using-statement

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

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/

相关文章:

c# - 您可以 [过时] Razor 中的 DisplayTemplate 吗?

c# - 从异步方法设置时,AsyncLocal 的值不正确

c# - 如何从现有的 .edmx 文件连接到数据库?

c# - 映射到现有的数据库表

c# - FluentFtp Azure ftp 用户在几次成功连接后无法登录

c# - 为什么在终结器中调用 Dispose() 会导致 ObjectDisposedException?

powershell - 我/我需要如何处置自定义PSObject?

.net-core - .NET 核心 POSIX IPC

msbuild - 如何通过 msbuild/msdeploy 部署 .net core rc2 项目?

c# - 无法在单元测试中访问已处置的对象