Search code examples
c#garbage-collectionmanaged

Dispose and memorystream


I have the following code that gets called 4 times a second and updates the background of a grid. When i don't dispose of of the memory stream, the memory output usage slowly grows and falls. MemoryStream has a Dispose function, But if I call it even after i dispose the Source Bitmap, the background is just white.

Do i need to dispose the stream? And if I do, what am I doing wrong?

private void Viewer_OnUpdate(object self, Bitmap sourceBitmap, Int32Rect cropArea)
    {
        if (sourceBitmap == null)
        {
            return;
        }

        this.Dispatcher.BeginInvoke(DispatcherPriority.Render,
            new Action(
                () =>
                    {
                        MemoryStream stream = new MemoryStream();
                        sourceBitmap.Save(stream, ImageFormat.Bmp);
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.BeginInit();
                        stream.Seek(0, SeekOrigin.Begin);
                        bitmapImage.StreamSource = stream;
                        bitmapImage.EndInit();
                        this.GridContainer.Background =
                            new ImageBrush(new CroppedBitmap(bitmapImage,cropArea));
                        sourceBitmap.Dispose();
                    }));
    }

Note: i'm dispatching because the calling event is always from a Non-UI thread


Solution

  • From MSDN documentation for BitmapImage (emphasis is mine):

    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.