.NET Core Dispose 实现

.NET Core Dispose implementation

我对如何正确实施 Dispose 模式有些困惑。

我有一个 class:

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;
    }
}

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

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

您正确处理了对象。作为参考,这是完整处理的 Visual Studio 片段:

    #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.