UnmanagedMemoryStream 处置和内存泄漏

发布于 2024-11-30 23:56:22 字数 453 浏览 1 评论 0原文

考虑以下代码片段,并忽略缺少 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

想念有你 2024-12-07 23:56:22

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.

夜声 2024-12-07 23:56:22

除了乔恩的回答之外 - 将方法更改为非静态将不会有任何效果。事实上,静态方法中有一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文