Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c# - When to dispose and why?

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?)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...