为什么 MS 工具生成的强类型数据集不关闭流?
Why Strongly Typed DataSets generated by MS tool don't close streams?
我刚刚在 xsd 数据集中找到了那个方法。
[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 个流,但没有使用 "using" clausule/closing 它们。这是为什么?
它还在文件顶部说
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
所以我认为我不应该自己修复它。谁能解释一下? :) 谢谢
生成的代码不是创建三个流,而是创建一个流、一个流编写器和一个流 reader。 "stream" 只是一个 MemoryStream
,它提供了一个流接口,但实际上只是一个内存缓冲区的包装器。
通常 .Dispose()
流(或使用 using
块)是有意义的,因为流正在包装一些需要释放的资源(如文件句柄或 TCP 套接字),并且您还需要禁用该流以防止进一步使用。但是由于这只是一个MemoryStream
,并没有真正管理外部资源,它只是存在于这个方法的范围内,其他代码无法访问流,所有.Dispose()
会做的是 运行 一些禁用流的逻辑,这并不是很有用。所以正常的垃圾收集就足以进行清理了。
请注意,我并不是在提倡不应该处置内存流;对任何 IDisposable
使用 using
块是个好主意,因为您不知道实现细节,并且应该假设您应该在完成对象后清理资源。但在这种情况下不处置可能是一种优化。
编辑:
尊敬的 John Skeet 对类似的问题进行了权衡:
我刚刚在 xsd 数据集中找到了那个方法。
[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 个流,但没有使用 "using" clausule/closing 它们。这是为什么? 它还在文件顶部说
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
所以我认为我不应该自己修复它。谁能解释一下? :) 谢谢
生成的代码不是创建三个流,而是创建一个流、一个流编写器和一个流 reader。 "stream" 只是一个 MemoryStream
,它提供了一个流接口,但实际上只是一个内存缓冲区的包装器。
通常 .Dispose()
流(或使用 using
块)是有意义的,因为流正在包装一些需要释放的资源(如文件句柄或 TCP 套接字),并且您还需要禁用该流以防止进一步使用。但是由于这只是一个MemoryStream
,并没有真正管理外部资源,它只是存在于这个方法的范围内,其他代码无法访问流,所有.Dispose()
会做的是 运行 一些禁用流的逻辑,这并不是很有用。所以正常的垃圾收集就足以进行清理了。
请注意,我并不是在提倡不应该处置内存流;对任何 IDisposable
使用 using
块是个好主意,因为您不知道实现细节,并且应该假设您应该在完成对象后清理资源。但在这种情况下不处置可能是一种优化。
编辑:
尊敬的 John Skeet 对类似的问题进行了权衡: