关于c#:为什么MS工具生成的强类型数据集不会关闭流?

Why Strongly Typed DataSets generated by MS tool don't close streams?

本问题已经有最佳答案,请猛点这里访问。

我刚刚在xsd数据集中找到了该方法。

1
2
3
4
5
6
7
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected override System.Xml.Schema.XmlSchema GetSchemaSerializable() {
            global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream();
            this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null));
            stream.Position = 0;
            return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null);                
        }

它创建3个流,但不使用"使用"子句/将其关闭。 这是为什么?
它还说,在文件的顶部,

1
2
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.

所以我相信我不应该自己修复它。 谁能解释? :) 谢谢


生成的代码不是创建三个流,而是创建一个流,一个流编写器和一个流读取器。"流"只是一个MemoryStream,它提供了一个流接口,但实际上只是一个内存缓冲区的包装器。

通常,.Dispose()流(或使用using块)是有意义的,因为流包装了一些需要释放的资源(例如文件句柄或TCP套接字),并且还需要从进一步使用。但是,由于这只是一个MemoryStream,实际上并没有管理外部资源,它只存在于此方法的范围内,并且其他代码也无法访问该流,因此所有.Dispose()要做的就是运行一些逻辑来禁用流,这并不是真正有用的。因此,正常的垃圾收集就足以进行清理。

请注意,我并不是在主张不要丢弃内存流。对任何IDisposable使用using块是一个好主意,因为您不知道实现细节,而应该假定在完成对象处理后应该清理资源。但是在这种情况下不进行处置可能是一种优化。

编辑:

尊敬的约翰·斯基特(John Skeet)提出了类似的问题:

https://stackoverflow.com/a/234257/119549