- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement IDisposable Design Pattern in C#?
We should use an IDisposable design pattern (or Dispose Pattern) when we need to dispose of unmanaged objects.
For implementing the IDisposable design pattern, the class which deals with unmanaged objects directly or indirectly should implement the IDisposable interface.And implement the method Dispose declared inside of the IDisposable interface. We do not directly deal with unmanaged objects. But we deal with managed classes, which deals directly with unmanaged objects. For example, File handlers, connection string, HTTP streams, etc.
Important aspect of this pattern is that it makes easier for inherited classes to follow the IDisposable design pattern. And it is because of the implementation of an overridable Dispose method. This pattern also suggests the use of the Finalizer method (or destructor in c#). However, if we use the Finalizer, it should be managed properly due to its performance implications.
Example
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)); } }