.NET Core Dispose实现

时间:2019-01-08 15:44:58

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

我对如何正确实现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;
    }
}

我的实现是正确的吗?

1 个答案:

答案 0 :(得分:1)

您没有向我们展示创建_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