RenderTargetBitmap Memory Leak

拥有回忆 提交于 2019-12-23 13:12:34

问题


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.


回答1:


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();



回答2:


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



来源:https://stackoverflow.com/questions/6713868/rendertargetbitmap-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!