Sam Saffron
Sam Saffron

Reputation: 131112

Image.FromStream does not hold a ref to the underlying stream

I have some code that does

MemoryStream ms = new MemoryStream();
...
return Image.FromStream(ms);

It fails in very eclectic ways since the Image object does not hold a ref to the stream, so it can get disposed if the GC kicks in which results in GDI+ errors.

How do I work around this (without saving the stream to disk, or altering my method sigs) ?

Upvotes: 3

Views: 1771

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500385

This seems highly unlikely to me - it would cause a problem for almost any use of Image.FromStream.

It seems more likely to me that something's disposing of your MemoryStream, which it shouldn't.

Could you provide a short but complete program which demonstrates the problem? Forcing garbage collection should make it relatively easy to reproduce - you could even create your own class deriving from MemoryStream with a finalizer to show whether or not it really is being collected (well, finalized at least).

Upvotes: 1

casperOne
casperOne

Reputation: 74530

There isn't a way to do it without changing your code somewhat. The Remarks section for the documentation for the static FromStream method on the Image class states:

You must keep the stream open for the lifetime of the Image.

That being said, you have to make sure that while the Image is accessing the Stream, the stream is open. It would also appear (looking through Reflector) that the FromImage method doesn't actually cause the Image instance to hold onto a reference to the Stream the image was loaded from.

That being said, you to somehow link the image and the MemoryStream (or Stream) together so that it doesn't get GCed. If don't really retain "ownership" of the image (it is passed around), then I recommend that you create a data structure which will hold the reference to the Image and to the Stream and pass the two around in tandem.

Upvotes: 1

Related Questions