我正在尝试使用 RenderTargetBitmap 渲染图像
每次我从 RenderTargetBitmap 创建一个实例来渲染图像时,内存都会增加,完成后内存永远不会释放
这是代码:

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

请我需要帮助
我怎样才能释放内存
并感谢大家。

最佳答案

如果您使用 Resource Monitor 监控 RenderTargetBitmap 类的行为,您可以看到每次调用该类时,您都会损失 500KB 的内存。我对你的问题的回答是:不要多次使用 RenderTargetBitmap

您无法释放 RenderTargetBitmap 的已用内存。

如果您确实需要使用 RenderTargetBitmap 类,只需在代码末尾添加这些行。

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

这可能会解决您的问题:
    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();

关于c# - RenderTargetBitmap 内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6713868/

10-10 10:41