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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top