RenderTargetBitmap memory leak

I try to make an image using RenderTargetBitmap every time I create an instance from RenderTargetBitmap to render the image, the amount of memory increases, and when this is done, the memory is never released and this is the code:

RenderTargetBitmap rtb = new RenderTargetBitmap((int)(renderWidth * dpiX / 96.0), (int)(renderHeight * dpiY / 96.0), dpiX, dpiY, PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual(); using (DrawingContext ctx = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(target); ctx.DrawRectangle(vb, null, new System.Windows.Rect(new Point(0, 0), new Point(bounds.Width, bounds.Height))); } rtb.Render(dv); 

I need help how can I free memory and thanks to everyone.

+4
source share
2 answers

if you track the behavior of the RenderTargetBitmap class using the Resource Monitor , you can see every time this class is called, you lose 500 KB of your memory. my answer to your question: Do not use the RenderTargetBitmap class so many times

You cannot fire an event with saved RenderTargetBitmap memory.

If you really need the RenderTargetBitmap class, just add these lines at the end of your code.

  GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() 

this may solve your problem:

  RenderTargetBitmap rtb = new RenderTargetBitmap((int)(renderWidth * dpiX / 96.0), (int)(renderHeight * dpiY / 96.0), dpiX, dpiY, PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual(); using (DrawingContext ctx = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(target); ctx.DrawRectangle(vb, null, new System.Windows.Rect(new Point(0, 0), new Point(bounds.Width, bounds.Height))); } rtb.Render(dv); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); 
+3
source

This is not a real memory leak, at least in my experience. You will see how memory usage works in the task manager, but the garbage collector should take care of it when it really needs it (or you can call GC.Collect () yourself to make it happen). However, if you are drawing shapes, DrawingContext / DrawingVisuals are not ideal in WPF. You will be much better off using vector graphics, and you will have a number of side benefits, including scalability and the absence of this memory problem.

See my answer to a similar question here: The program takes up too much memory

0
source

All Articles