What is IDisposable interface & finalize dispose pattern in GC?

Destructor/Finalize can be used to Clean up unmanaged code, but if we use destructor in our .Net application then the number of objects appearing in Gen 1 and Gen 2 is higher than no of objects in Gen 0.This is because when GC runs then it firstly ask to a class that “Do you have a Destructor” if class returns Yes then GC will move the objects to next generation bucket, and will wait to the destructor to run and then it will clear the objects. That’s why we are getting more objects in Gen 1, Gen 2 as compare to Gen 0;

 

We can understand it with the help  of below example-

private void button1_Click(object sender, EventArgs e)

{

for(int i=0;i<1000000;i++)

{

cls obj=new cls();

}

}

}

public class cls1

{

~cls()

{//clean up unmanaged code}

}

To solve this problem we have to use IDisposable interface–

private void button1_Click(object sender, EventArgs e)

{

for(int i=0;i<1000000;i++)

{

cls obj=new cls();

obj Dispose();

}

}

}

public class cls1 : IDisposable

{

~cls()

{clean up unmanaged code}

public void Dispose()

{//write your unmanaged code

GC.SuppressFinalize(true);

}

}

In above example we can eliminate ~cls1() but we still not removed because if developer forget to call obj.Dispose() then also application should work properly.

Advertisements

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 )

Google+ photo

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

Connecting to %s