Tuesday, September 23, 2008

Finalize vs Dispose in C#

-You cannot override the Finalize method in the C#, instead, you have to use destructor syntax to implement the Finalize method.

It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface. The IDisposable interface requires its implementers to define one method, named Dispose(), to perform whatever cleanup you consider to be crucial. The availability of Dispose() is a way for your clients to say, "Don’t wait for the destructor to be called; do it right now."
If you provide a Dispose() method, you should stop the garbage collector from calling your object’s destructor. To stop the garbage collector, you call the static method, GC.SuppressFinalize(), passing in this reference for your object. Your destructor can then call your Dispose() method. Thus, you might write:

using System;
class Testing : IDisposable
{
bool is_disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!is_disposed) // only dispose once!
{
if (disposing)
{
Console.WriteLine("Not in destructor, OK to reference
other objects");
}
// perform cleanup for this object
Console.WriteLine("Disposing...");
}
this.is_disposed = true;
}
public void Dispose()
{
Dispose(true);
// tell the GC not to finalize
GC.SuppressFinalize(this);
}
~Testing()
{
Dispose(false);
Console.WriteLine("In destructor.");
}
}

Implementing the Close method
For some objects, you’d rather have your clients call the Close() method. (For example, Close makes more sense than Dispose() for file objects.) You can implement this by creating a private Dispose() method and a public Close() method and having your Close() method invoke Dispose().

The using statement
Because you cannot be certain that your user will call Dispose() reliably, and because finalization is nondeterministic (meaning you can’t control when the garbage collector will run), C# provides a using statement, which ensures that Dispose() will be called at the earliest possible time. The idiom is to declare which objects you are using and then to create a scope for these objects with curly braces. When the close brace is reached, the Dispose() method will be called on the object automatically:
using System.Drawing;
class Tester
{
public static void Main()
{
using (Font theFont = new Font("Arial", 10.0f))
{
// use theFont
} // compiler will call Dispose on theFont
Font anotherFont = new Font("Courier",12.0f);
using (anotherFont)
{
// use anotherFont
} // compiler calls Dispose on anotherFont
}
}

In the first part of this example, the Font object is created within the using statement. When the using statement ends, Dispose() is called on the Font object.
In the second part of the example, a Font object is created outside of the using statement. When we decide to use that font, we put it inside the using statement and when that statement ends, once again Dispose() is called.
The using statement also protects you against unanticipated exceptions. No matter how control leaves the using statement, Dispose() is called. It is as if there were an implicit try-catch-finally block.

12 comments:

Anonymous said...

movie about love [url=http://moviestrawberry.com/films/film_i_could_never_be_your_woman/]i could never be your woman[/url] castlevania movie updates http://moviestrawberry.com/hqmoviesbygenres/download-genre_drama-movies/?page=70 old western movie stars
movie theaters in yonkers [url=http://moviestrawberry.com/films/film_eden_log/]eden log[/url] latest james bond movie http://moviestrawberry.com/hqmoviesbycountry/country_usa/?page=16 paullina iowa movie
the invasion movie info [url=http://moviestrawberry.com/films/film_murder_rooms_the_photographer_s_chair/]murder rooms the photographer s chair[/url] movie double cross
cfnm movie scenes [url=http://moviestrawberry.com/films/film_the_maltese_falcon/]the maltese falcon[/url] movie flash exhibitionism http://moviestrawberry.com/films/film_renegades_of_the_rio_grande/ the sinking of japan the movie
dhol movie pictures [url=http://moviestrawberry.com/films/film_is_anybody_there/]is anybody there[/url] horror movie sheep http://moviestrawberry.com/hqmoviesbyyear/year_2009_high-quality-movies/?page=13 nude female movie stars

Anonymous said...

roughie movie [url=http://moviestrawberry.com/films/film_cinderella_ii_dreams_come_true/]cinderella ii dreams come true[/url] missoula movie http://moviestrawberry.com/films/film_curly_sue/ blurry dvd is it caused by dvd burner sonic or movie maker
color purple movie scripts [url=http://moviestrawberry.com/films/film_death_in_love/]death in love[/url] movie once dvd http://moviestrawberry.com/hqmoviesbygenres/download-genre_horror-movies/?page=10 compositing software used for transformer movie
previews of movie splash with j paulik [url=http://moviestrawberry.com/films/film_the_portrait_of_a_lady/]the portrait of a lady[/url] desktop movie wallpapers
american movie weekend box office [url=http://moviestrawberry.com/films/film_flight_of_the_navigator/]flight of the navigator[/url] windigo movie http://moviestrawberry.com/films/film_vicky_cristina_barcelona/ oxford movie uk
every movie made list [url=http://moviestrawberry.com/films/film_antichrist/]antichrist[/url] music from the movie halloween http://moviestrawberry.com/films/film_ice_princess/ wild side movie

Anonymous said...

nice articles...

Anonymous said...

q movie [url=http://moviestrawberry.com/films/film_bound_for_glory/]bound for glory[/url] best rated free full length movie site http://moviestrawberry.com/films/film_the_relief_of_belsen/ second run movie theaters houses
across the universe movie theater [url=http://moviestrawberry.com/films/film_van_wilder_freshman_year/]van wilder freshman year[/url] venus the movie http://moviestrawberry.com/films/film_1408/ montreal movie listings
indiana jones first movie pictures [url=http://moviestrawberry.com/films/film_phantom_racer/]phantom racer[/url] hot box invasion movie
how to write a movie treatment [url=http://moviestrawberry.com/films/film_garden_state/]garden state[/url] casting for wonder woman movie http://moviestrawberry.com/films/film_retread/ free big tit movie post
el cid the movie [url=http://moviestrawberry.com/films/film_telefon/]telefon[/url] tron the movie http://moviestrawberry.com/countries/?page=60 thje best movie ever made

Anonymous said...

I love c-sharpexpertizer.blogspot.com! Here I always find a lot of helpful information for myself. Thanks you for your work.
Webmaster of http://loveepicentre.com and http://movieszone.eu
Best regards

Anonymous said...

Hi there, I enjoy reading all of your post. I wanted to write
a little comment to support you.
Review my blog post :: red hot elevator ride coins

Anonymous said...

Thank you for the good writeup. It in fact was a amusement account it.

Look advanced to far added agreeable from you! By the way, how could we communicate?
Here is my weblog ; visit this website

Anonymous said...

Great website you have here but I was curious about if you knew of any forums that cover the same topics
discussed in this article? I'd really like to be a part of group where I can get comments from other experienced individuals that share the same interest. If you have any recommendations, please let me know. Appreciate it!

Feel free to surf to my site: quit smoking fast

Anonymous said...


Amazing web-site you possess going here. i SUCK i KNOW

Anonymous said...

This blog was... how do you say it? Relevant!! Finally I've found something that helped me. Appreciate it!

Visit my blog - Work From Home Opportunities

Anonymous said...

Great post.

Feel free to visit my site xxx videos

Anonymous said...

Thanks for sharing your thoughts on sprint. Regards

Also visit my blog post :: Pure Morning Pussy Delight

About Me

Bangalore, Karnataka, India