I have this function which returns an Image within the function the image is created using the Image.FromStream method
According to MSDN:
You must keep the stream open for the lifetime of the Image
So I'm not closing the stream(if I do close the steam a GDI+ exception is thrown from the returned image object). My question is whether the stream will be closed/disposed when Image.Dispose() is called somewhere else on the returned Image
public static Image GetImage(byte[] buffer, int offset, int count)
{
var memoryStream = new MemoryStream(buffer, offset, count);
return Image.FromStream(memoryStream);
}
As suggested in one of the answers, using is not the way to go, since it throws an exception:
public static Image GetImage(byte[] buffer, int offset, int count)
{
using(var memoryStream = new MemoryStream(buffer, offset, count))
{
return Image.FromStream(memoryStream);
}
}
public static void Main()
{
var image = GetImage(args);
image.Save(path); <-- Throws exception
}
- According to some people explicitly disposing/closing a MemoryStream is not necessary as it doesn't use any unmanaged resources others say the opposite thing so its kind of a dilemma.
- Image.Dispose method doesn't dispose the stream ftom which the Image was created
- The Image class doesn't hold any reference to the Stream passed to Image.FromStream method so the stream will eventually be collected by the GC...? Hence the exception in Image.Save method
- Return a wrapper class which contains a reference to the stream and the Image created by it hence enabling us to dispose both of them...? or simply use the Tag property to keep a reference to the parent stream...?
- This problem only seems to happen when using the MemoryStream. If the image is created from ConnectStream nothing bad happens even if the parent stream is disposed.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…