如何在 C# 中實現 IDisposable 設計模式?


在我們處理非託管物件時我們需要使用一個 IDisposable 設計模式(或處置模式)。

為了實現 IDisposable 設計模式,直接或間接處理非託管物件的類應該實現 IDisposable 介面。並在 IDisposable 介面中實現已宣告 Dispose 方法。我們沒有直接處理非託管物件。但是我們處理處理非託管物件的託管類。例如,檔案處理程式、連線字串、HTTP 流等。

此模式的一個重要方面是,它使繼承類更輕鬆地遵循 IDisposable 設計模式。這是由於實現了一個可重寫的 Dispose 方法。此模式還建議使用 Finalizer 方法(在 C# 中即解構函式)。但是,如果我們使用 Finalizer,應當由於其效能影響妥善管理。

示例

static class Program {
   static void Main(string[] args) {
      using var serviceProxy = new ServiceProxy(null);
      serviceProxy.Get();
      serviceProxy.Post("");
      Console.ReadLine();
   }
}
public class ServiceProxy : System.IDisposable {
   private readonly HttpClient httpClient;
   private bool disposed;

   public ServiceProxy(IHttpClientFactory httpClientFactory) {
      httpClient = httpClientFactory.CreateClient();
   }
   ~ServiceProxy() {
      Dispose(false);
   }
   public void Dispose() {
      Dispose(true);
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing) {
      if (disposed) {
         return;
      }

      if (disposing) {
         // Dispose managed objects
         httpClient.Dispose();
      }
      // Dispose unmanaged objects
      disposed = true;
   }
   public void Get() {
      var response = httpClient.GetAsync("");
   }
   public void Post(string request) {
      var response = httpClient.PostAsync("", new StringContent(request));
   }
}

更新日期: 25-Nov-2020

2K+ 瀏覽

啟動您的職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.