The documentation of BitmapImage.StreamSource says:
Set the CacheOption property to BitmapCacheOption.OnLoad if you wish to close the stream after the BitmapImage is created. The default OnDemand cache option retains access to the stream until the bitmap is needed, and cleanup is handled by the garbage collector.
Since you set CacheOption
accordingly, imgBrush
should no longer require access to the stream after EndInit
(at least, that's how I would interpret the quoted paragraph), so your code looks correct to me.
PS: Yes, it's good practice to dispose all IDisposable
s, but, in your case, it's just a memory stream. In contrast to a file stream or a database connection, a memory stream does not have any unmanaged resources that need to be released. In fact, according to the reference source, all that MemoryStream.Dispose
does is to ensure that an exception is thrown if you try to read it again, so I wouldn't lose any sleep over it.