Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to dispose and why?

Tags:

c#

dispose

I asked a question about this method:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    TextWriter textWriter = new StreamWriter(filename);

    xmlSerializer.Serialize(textWriter, toSerialize);
    textWriter.Close();
}

in the response I got this as an added remark:

Make sure you always dispose disposable resources such as streams and text readers and writers. This doesn't seem to be the case in your SerializeObject method.

So, I can tell that this is going to seem super lame for someone who has been coding C# for a year or two, but why do I have to dispose it?

Is see that testWriter has a dispose method, but shouldn't garbage collection take care of that? I came from Delphi to C#. In Delphi I had to clean up everything, so this is not a case of me wanting to be lazy. I just was told that if you force freeing up the memory that your objects take then it can cause bad stuff. I was told to "Just let the garbage collector do it".

  1. So, why do I need to call dispose? (My guess is that it is because textWriter hits the disk.)
  2. Is there a list of objects I need to be careful with? (Or an easy way to know when I need to call dispose?)
like image 950
Vaccano Avatar asked Oct 21 '10 18:10

Vaccano


People also ask

Why is disposing important?

With waste being properly disposed of, our environment is cleaner, meaning there are fewer health risks and hazards around to affect us. This includes not having our surroundings polluted and, instead, ensures that our society remains as healthy as possible.

Why do we do waste disposal?

The main benefits of effective waste disposal include: Environmental protection – from pollution or contamination. Money generation – companies may buy recyclable materials due to their value. Additionally, the waste management industry creates employment opportunities.

When should you throw the waste?

we should throw garbage in covered bins because if we throw garbage here and there then many types of pollution will occur ,diseases will arise so to escape from these things we should throw garbage in covered bins.

What is disposal process?

waste disposal, the collection, processing, and recycling or deposition of the waste materials of human society.


2 Answers

The rule of thumb here is pretty simple: always call Dispose() on objects that implement IDisposable (not all objects do). You won't always know the reason why an object had to implement Dispose, but you should assume that it is there for a reason.

The easiest way to make sure you do this is through using:

using (TextWriter tw = new StreamWriter(fileName))
{
   // your code here
}

This will call Dispose() automatically at the end of the using block (it's fundamentally the same as using a try/catch/finally with the Dispose() in the finally block).

For more information on how Dispose works with garbage collection, see here.

like image 78
Jon B Avatar answered Oct 10 '22 11:10

Jon B


You are correct that for properly written code the GC will eventually clean up the native resources. The object will have a finalizer, and during finalization will free up the necessary native resources.

However when this happens is very non-deterministic. Additionally it's a bit backwards because you're using the GC which designed to handle managed memory as a means to manage native resources. This leads to interesting cases and can cause native resources to stay alive much longer than anticipated leading to situations where

  • Files are open long after they are no longer used
  • Resource handles can run out because the GC doesn't see enough memory pressure to force a collection and hence run finalizers

The using / dispose pattern adds determinism to the cleanup of native resources and removes these problems.

like image 36
JaredPar Avatar answered Oct 10 '22 12:10

JaredPar