我问一个问题有关此方法
//保存对象到磁盘公共静态无效SerializeObject< T>(这件T toSerialize,字符串文件名) {的XmlSerializer XmlSerializer的=新的XmlSerializer(toSerialize.GetType()); 的TextWriter的TextWriter =新的StreamWriter(文件名); xmlSerializer.Serialize(的TextWriter,toSerialize); textWriter.Close(); }在我这还有一个额外的言论响应:
请确保您始终一次性处置等资源流和文本的读者和作家。这似乎并不在你的SerializeObject方法的情况。
所以,我可以告诉大家,这会显得超级跛脚有人谁已编码C#为一年或两年,可是为什么我必须处理掉呢?
时看到 testWriter 具有Dispose方法,但不应垃圾收集采取照顾?我从德尔福为C#。在Delphi中,我不得不收拾一切,所以这不是我的想偷懒的情况。我只是被告知,如果你强迫腾出了那么你的对象将存储它可能会导致不好的东西。有人告诉我,让垃圾回收器做它。
您是更正为正确写入代码GC最终将清理本地资源。该对象将有一个终结,和定稿期间将腾出必要的本地资源。
然而,当发生这种情况是非常不确定性。此外,它是一个有点倒退,因为你使用的用来处理管理内存来管理本地资源的一种手段GC。这导致了有趣的情况,并可能导致本土资源活路比预期更长的时间,导致情况下
- 文件打开后不久他们不再使用
- 资源句柄可以跑出来,因为GC没有看到足够的内存压力,迫使一个集合,因此运行终结
在使用/ 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".
解决方案
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.
更多推荐
当处置,为什么?
发布评论