This is a mirror of official site: http://jasper-net.blogspot.com/

Disposable Pattern in .NET

| Sunday, February 28, 2010
Garbage collector (GC) is a blessing in .NET, if you happen to program in C++ in the past, where it was one of the prime responsibility of a developer was to manage the heap. That means when ever an object is created on the heap, it has to be deleted in the corresponding method or in the destructor, if the life is object long. And if he/she forgot to do so, then the nightmare begins in the form of memory leaks and troubleshooting may take hours and some times even days. But that's the story of the past, we as a C# developers are blessed, because we have a world class Garbage Collector comes right out of the box with .NET framework. What does it mean?? That means we need not to worry about deleting/disposing the objects being created on the heap, and GC, at runtime manage the heap, and its robust algorithm sees when some object is no longer needed, it silently dispose it off. Very clever, but you know what, not that clever. It doesn't know how to close the resources like a Database connections,  file handle when it is no more needed, doesn't know what to do when the Network connection needs to be released or closed etc. etc. First thing that would come into your mind, why don't we use the finalizer/destructor to take care of this scenario?? Like we close these resource handles in the finalizers, how's that?? You can do so, but it will not work, why?? due to the GC’s non-deterministic behavior, it may take longer than expected that the destructor/finalizer will be called, and there will be a deadlock, that is you might need to reuse some resource, and since the objects destructor is not called, the object is not releasing it, you are stuck, complete deadlock. So what we do now?? Good news is, you can do it elegantly with the help of proper usage of Disposable Pattern. Before going into the details of this pattern, lets first take a look at what are disposable objects and how the .NET framework facilitates us in this regard.

IDisposable Objects

Any custom object that owns certain resources and wants to participate in the disposable mechanism, has to implement IDisposable interface. What does that mean?? Does the CLR will  take care of disposing the object automatically. Not really, it is the consumers responsibility to call the Dispose method, as soon as the object is no more needed. .NET framework itself has created many disposable classes as shown in Figure-1. All of these classes if you look at them are responsible for interacting system resources, like memory, file system, network stream, pipes etc. etc. That's why they all are implemented the IDisposable interface, so the consumer of these types should be aware of its usage and release them as soon as they are done.

Read more: GeeksCafe.net

Posted via email from jasper22's posterous

0 comments: