代码之家  ›  专栏  ›  技术社区  ›  Oleg Sh

.NET核心部署实现[重复]

  •  0
  • Oleg Sh  · 技术社区  · 6 年前

    我对如何正确实现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 回复  |  直到 6 年前
        1
  •  1
  •   Yennefer    4 年前

    你没有告诉我们你在哪里创造 _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 .