gpt4 book ai didi

使用 RenderTargetBitmap 的 WPF 内存泄漏?

转载 作者:行者123 更新时间:2023-12-04 15:58:22 24 4
gpt4 key购买 nike

我对 WPF 代码中的内存泄漏感到有些困惑。我正在将一些 3D 几何图形渲染到几个 RenderTargetBitmap,然后将其中的每一个渲染到一个大的主 RenderTargetBitmap。但是当我这样做时,我会遇到内存泄漏,一两分钟后我的应用程序就会崩溃。

我在以下简化的代码段中重现了错误。

   private void timer1_Tick(object sender, EventArgs e) {
// if first time, create final stitch bitmap and set UI image source
if (stitch == null) {
stitch = new RenderTargetBitmap(1280, 480, 96, 96, PixelFormats.Pbgra32);
myImage.Source = stitch;
}

// create visual and render to img1
Rect rect = new Rect(new Point(160, 100), new Size(320, 80));
DrawingVisual dvis = new DrawingVisual();
using (DrawingContext dc = dvis.RenderOpen()) {
dc.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);
}
RenderTargetBitmap img1 = new RenderTargetBitmap(640, 480, 96, 96, PixelFormats.Pbgra32);
img1.Render(dvis);

// create visual and render to final stitch
DrawingVisual vis = new DrawingVisual();
using (DrawingContext dc = vis.RenderOpen()) {
dc.DrawImage(img1, new Rect(0, 0, 640, 480));
}

stitch.Clear();
stitch.Render(vis);
}

任何人都可以看到这里有什么明显的问题吗?为什么这段代码会出现严重的内存泄漏?

最佳答案

如果您监控 RenderTargetBitmap 的行为类使用 资源监控 ,你可以看到每次调用这个类,你都会损失 500KB 的内存。我对您问题的回答是:不要使用 RenderTargetBitmap上课这么多次

你甚至不能释放RenderTargetBitmap的Used Memory。

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

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

这可能会解决您的问题:
private void timer1_Tick(object sender, EventArgs e) {
// if first time, create final stitch bitmap and set UI image source
if (stitch == null) {
stitch = new RenderTargetBitmap(1280, 480, 96, 96, PixelFormats.Pbgra32);
myImage.Source = stitch;
}

// create visual and render to img1
Rect rect = new Rect(new Point(160, 100), new Size(320, 80));
DrawingVisual dvis = new DrawingVisual();
using (DrawingContext dc = dvis.RenderOpen()) {
dc.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);
}
RenderTargetBitmap img1 = new RenderTargetBitmap(640, 480, 96, 96, PixelFormats.Pbgra32);
img1.Render(dvis);

// create visual and render to final stitch
DrawingVisual vis = new DrawingVisual();
using (DrawingContext dc = vis.RenderOpen()) {
dc.DrawImage(img1, new Rect(0, 0, 640, 480));
}

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
stitch.Clear();
stitch.Render(vis);
}

关于使用 RenderTargetBitmap 的 WPF 内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com