WPF:如何在循环中多次克隆图像?

WPF: How to clone an image multiple times in a loop?

目标:多次克隆图像。

问题:出现异常:

An exception of type 'System.OutOfMemoryException' occurred in PresentationCore.dll but was not handled in user code Additional information: Insufficient memory to continue the execution of the program.

问:如何做才正确?

代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        double width = 1000;

        Ellipse ellipse = new Ellipse();
        ellipse.Width = width;
        ellipse.Height = width;
        ellipse.Fill = Brushes.Red;
        ellipse.Arrange(new Rect(0, 0, width, width));

        RenderTargetBitmap rtb = new RenderTargetBitmap((int)width, (int)width, 96, 96, PixelFormats.Pbgra32);
        rtb.Render(ellipse);

        for (int i = 0; i < 1000; i++)
            rtb.Clone(); // Exception
    }
}

为获得最佳结果,您应该提出与现实问题相关的问题。简直令人难以置信,需要在这样一个紧密的循环中将位图克隆 1000 次。

也就是说,答案很简单:您的速度太快了,垃圾收集器跟不上。在达到堆的最大大小之前,它没有丢弃先前分配的内存。

您至少有两种可能的方法来解决问题。一种是更改循环,以便定期强制进行垃圾收集(例如,每次克隆位图时):

    for (int i = 0; i < 1000; i++)
    {
        rtb.Clone(); // Exception
        GC.Collect();
    }

或者,您可以 运行 项目作为 64 位进程,在这种情况下,它有足够的地址 space 用于分配 4GB 的空间。