RenderTargetBitmap Memory Leak

2019-06-27 14:19发布

am trying to render an image with RenderTargetBitmap every time i create an instance from RenderTargetBitmap to render image the memory increased and when am done the memory 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);

please i need help how can i release the memory and thanks for all.

2条回答
Bombasti
2楼-- · 2019-06-27 14:44

if you monitor behaviors of the RenderTargetBitmap class using Resource Monitor, you can see each time this class called, you lose 500KB of your memory. my Answer to your Question is: Dont use RenderTargetBitmap class so many times

You cant event release the Used Memory of RenderTargetBitmap.

If you really need using RenderTargetBitmap class, just add these lines at 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楼-- · 2019-06-27 14:52

This is not a true memory leak, at least in my experience. You'll see memory usage creep up in task manager, but the garbage collector should take care of it when it actually needs to (or you can call GC.Collect() yourself to see this happen). That said, if you're drawing shapes, DrawingContext/DrawingVisuals are not ideal in WPF. You'd be much better off using vector graphics and you would have a number of side benefits, including scalability and not seeing this memory usage issue.

See my answer to a similar question here: Program takes too much memory

查看更多
登录 后发表回答