Finalize vs Dispose

Posted on 05/02/2011. Filed under: Asp.Net Concepts |

Following the difference between Dispose and Finalize method,

1>CLR uses the Dispose and Finalize methods for performing garbage collection of runtime objects of .Net applications.

2>CLR has a Garbage Collector(GC) which periodically checks for unused and unreferenced objects in Heap.It call Finalize() method to free the memory used by such objects.

3>Dispose is another method which is invoked by Garbage Collector to release the memory occupied by an object.Dispose method needs to be explicitly called in code for removing an object from Heap.

4>Dispose method can be invoked only by the classes that IDisposable interface.

Summary:

Both of them are used to free the unused objects an unreferenced object from the memory but

Finalize—Implicitly call GC by CLR Even we can’t see this key in C#

Dispose—-Explicitly Call GC by CLR We have key word for this

Design Pattern : If your classes use unmanaged resources you need to implement both Dispose & Finalize. Dispose() is called by user code that is the code that is using your class.
Finalize/Destructor cannot be called by User code it’s called by Garbage Collector

Advertisement

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.