UnmanagedMemoryStream 处置和内存泄漏
考虑以下代码片段,并忽略缺少 using 子句或显式处置:
public static Image GetImage(string imageName)
{
Image image = null;
Stream unmanagedMemoryStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imageName);
image = Image.FromStream(unmanagedMemoryStream);
return image;
}
何时会对 unmanagementMemoryStream 调用 Dispose()?如果将包含方法设为非静态,这会如何改变?在这种情况下是否可能发生非托管内存泄漏?
Considering the following code snippet and overlooking the lack of a using clause or an explicit disposal:
public static Image GetImage(string imageName)
{
Image image = null;
Stream unmanagedMemoryStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imageName);
image = Image.FromStream(unmanagedMemoryStream);
return image;
}
When will Dispose() be called on unmanagedMemoryStream? How would this change if the containing method was made non-static? Is a leak of unmanaged memory possible in this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当
image
被释放时,将会释放流 -Image.FromStream
有效地获取它所给定的流的所有权。特别是,如果您确实在此处的
using
语句中处理流,则图像将无法使用,至少对于某些图像类型而言是如此。When
image
is disposed, that will dispose of the stream -Image.FromStream
effectively takes ownership of the stream it's given.In particular, if you did dispose the stream in a
using
statement here, the image would be unusable, at least for some image types.除了乔恩的回答之外 - 将方法更改为非静态将不会有任何效果。事实上,静态方法中有一个 Image 局部变量并不会改变任何东西 - 它只是堆栈上对堆上对象的引用。当方法退出时,引用将从堆栈中删除。因此,无论该方法是否是静态的,对于内存泄漏都不会产生任何影响。
这里内存泄漏的可能性是如果图像从未被释放并且从未被垃圾收集。
In addition to Jon's answer - changing the method to non-static will have no effect. The fact you have an Image local variable in a static method doesn't change anything - it's just a reference on the stack to an object on the heap. When the method exits, the reference is removed from the stack. So whether the method is static or not changes nothing in terms of memory leaking.
The possibility for memory leaking here is if the Image is never Disposed of and never Garbage Collected.