【问题标题】:.NET Core Dispose implementation [duplicate].NET Core Dispose 实现 [重复]
【发布时间】:2019-06-03 08:17:57
【问题描述】:

我有点困惑如何正确实现 Dispose 模式。

我有一堂课:

public class DomainActions : IDomainActions, IDisposable
{
    private HttpClient _client;

    public DomainActions(string baseAddress, string token)
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(baseAddress);
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    }

    public async Task<List<DomainDto>> GetDomainListAsync()
    {
        var requestStream = await _client.GetAsync("domains");
        var requestString = await requestStream.Content.ReadAsStringAsync();

        return ParseDomainListResponse(requestString);

    }

据我所知,我必须分配_client

public class DomainActions : IDomainActions
{
    //...
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private bool _disposed = false;
    public virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        if (disposing)
        {
            if (_client != null)
            {
                _client.Dispose();
                _client = null;
            }
        }
        _disposed = true;
    }
}

我的实现是正确的,够了吗?

【问题讨论】:

标签: c# .net .net-core dispose idisposable


【解决方案1】:

您没有向我们展示您在哪里创建 _client,但让我们弄清楚它是在构造函数中完成的。

您正在正确处理对象。作为参考,这是 Visual Studio sn-p 的完整处置:

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls
    
    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }

            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            disposedValue = true;
        }
    }
    
    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~A() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion

如果您的非托管资源不需要特殊清理并且可以用句柄表示,您应该使用SafeHandles,它更不容易出错且更简洁。如需更多信息,请查看Implement a Dispose Method

【讨论】:

  • 如果您有非托管资源:文档 (docs.microsoft.com/en-us/dotnet/standard/garbage-collection/…) 建议构造 System.Runtime.InteropServices.SafeHandle 对象而不是实现终结器
  • 如果您可以仅通过句柄折叠您的资源,那就是真的。有些情况需要您调用其他方法来执行清理。我发布了 Dispose 模式来向他们展示它应该如何工作。我改进了答案。谢谢:)
  • 他们的对象不仅没有无法用安全句柄表示的非托管资源,他们根本没有任何非托管资源。这些都没有帮助,甚至在这种情况下也有害
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多