문제

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