问题描述
我问一个有关此方法
//保存对象到磁盘
公共静态无效SerializeObject< T>(这件T toSerialize,字符串文件名)
{
的XmlSerializer XmlSerializer的=新的XmlSerializer(toSerialize.GetType());
的TextWriter的TextWriter =新的StreamWriter(文件名);
xmlSerializer.Serialize(的TextWriter,toSerialize);
textWriter.Close();
}
在我这还有一个额外的言论响应:
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".
- So, why do I need to call dispose? (My guess is that it is because
textWriter
hits the disk.) - Is there a list of objects I need to be careful with? (Or an easy way to know when I need to call dispose?)
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.
这篇关于当处置,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!