Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

First, you discovered that if you dispose the memory stream, the bitmap is affected, which means your ImageBrush seems white. So - don't dispose the memory stream.

Second, and more importantly, the memory consumption pattern you're seeing - more and more memory, then a sudden fall - is normal. That's what happens when the garbage collector runs at its own discretion. It's not a problem at all.

So don't dispose of the memory stream, let the garbage collector do its job, and don't worry about it.

Look, maybe this answer will help you.

MemoryStream in Using Statement - Do I need to call close()

If you put your MemoryStream in a using statement, you will not need to Dispose, because it will do it automatically ;)

I hope this helps

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top