What is the purpose of dispose method in .NET?You might
already know that garbage collector does automatic memory management and
clean up of resources. But there is a limitation.
Garbage collector releases memory occupied by managed resources i.e. resources that are managed in heap. But sometimes you might also use unmanaged resources. Few examples of such unmanaged resources include: Usage of stream reader to read a file Usage of stream writer to write contents into a file Establishing database connectivity These unmanaged
resources have to be released. Garbage collector gives you an option to
release unmanaged resources by using Finalize method. This is implicitly
called by the garbage collector before releasing an object and at that
point, all unmanaged resources accessed by the object will be freed. Other
than this, there is yet another option wherein the developer can explicitly
release unmanaged resources. This is done using dispose method. Consider that you have a text file called sample.txt and you prefer to read all lines of this text file using your C# program. For that, you will be using stream reader. Once the file is opened, read and then closed, you can release its memory using call to dispose method. This scenario is demonstrated below: Content of sample.txt:
Now you attempt
to create a C# program, read the contents of the file and release its
memory. This is done using the code shown below: Output of
this code will be: In this program,
you have explicitly called dispose method to perform the cleanup of StreamReader
which handles the text file. C# provides a better solution wherein you
will be using the statement Using in your code which will
take care of automatic disposal of that resource. This will
give the same output and it also takes care of calling dispose method
even if you have not explicitly called the method in the code shown above.
When you compile this code, it will be internally converted into the code
shown below: The best way of implementing Dispose method is to use Using statement rather than explicitly calling the Dispose() method.
|