IDisposable
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Contents |
The System.IDisposable interface defines a method of releasing unmanaged resources which have been allocated.
[edit]
Syntax
[edit]
Declaration syntax
[ComVisibleAttribute(true)] public interface IDisposable
[edit]
Method syntax
The Dispose method performs tasks defined by the application associated with releasing or resetting unmanaged resources. Resources like database connections, handles, files, and streams which are held by an instance of the class implementing this interface.
void Dispose ()
[edit]
Usage
Although this looks like a simple interface, it brings with it some complications due to digging into Garbage Collector (GC) territory. These complications can be minimized by sticking to these simple rules:
- Set unmanaged objects to
null - Call the
Disposemethods of managed objects - Stop the Garbage Collector from calling
finalizemethods on managed objects
- Set unmanaged objects to
class MyClass : IDisposable { FileStream myStream; //large object public MyClass (string filePath) { myStream = new FileStream (filePath, FileAccess.ReadWrite); } public void Dispose() { myStream.Dispose(); //remove myStream from the GC finalize queue GC.SuppressFinalize(myStream); } }
You should only use these classes inside a try-catch-finally statement or a using statement.
using(MyClass testObj = new MyClass("File.txt")) { //use testObj } //testObj is out of scope here as it has been disposed
[edit]