IDisposable is an interface defined in the System namespace. It is used to release managed and unmanaged resources. Implementing IDisposable interface compels us to implement 2 methods and 1 boolean variable –
- Public Dispose() : This method will be called by the consumer of the object when resources are to be released. This method will invoke the Dispose(bool disposing) method. We also notify the Garbage collector(GC) about the current object’s resource cleaning so that GC avoids doing it again at the end.
- Protected virtual Dispose(bool disposing): This method is the place where all the variables will be set to null. Also the derived class can override this method and release its own resources. The actual resource cleaning code is written in this method.
- Bool disposedValue: To ensure the dispose method is called once we use a boolean variable. The resource cleaning must not happen more than once.
The consumer of the object can call the first disposal method explicitly whenever the resources are no longer required. The garbage collector also cleans the object when it is out of scope. However, it is not capable of releasing a few objects such as files, streams, database connections, window handles, etc.
Syntax:
public interface IDisposable;
Disposable Interface Key Points :
- The class implementing IDisposable interface must implement the dispose method.
- A class having unmanaged resources should implement IDisposable interface.
- The client or consumer of the object can call the disposal method explicitly when the object is no longer required.
- Whenever a disposal method is called we need to notify the garbage collector about it so that it ignores that object during the cleaning of objects afterward.
- If a class has a destructor, the only code in there should be an invocation of Dispose(false) to clean any unmanaged resources at the end.
- The disposal method should be called only once. To ensure that we use a boolean variable.
- If a base class is implementing IDisposable interface the derived classes should not implement the interface again.
- The Derived class can override the dispose(bool disposing) method and release its resources.
Using Keyword:
While we can call the Dispose method manually or we can use the Using keyword provided by C#. The Using keyword automatically calls the Dispose method when the scope of the variable is over. It plays a crucial role in improving the performance during garbage collection.
Example 1:
- C#
Output:
No comments:
Post a Comment