WPF with GDI Memory growth

眉间皱痕 提交于 2019-12-24 08:48:43

问题


I'm writing an app in WPF (C#) that plots certain types of fractals. The data sets are 3d points and need to represented as single pixels. The user can click and drag to rotate the plots The amount of points varies but can be quite large (five million plots or more). Currently I am drawing onto a System.Drawing.Bitmap using a Graphics object then setting a WPF Image's Source property to that bitmap. The problem I have is that when i repeatedly redraw the image memory consumption steadily climbs. The Plot() method is called repeated when the user is dragging the mouse.

public void Plot()
{
    Graphics g = Graphics.FromImage(bmpCanvas);

    //Draw on the graphics object
    //...
    //...
    //...

    g.Dispose();
    Canvas.Source = loadBitmap(bmpCanvas);
    GC.Collect();
}

private BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}

Specifically I want to know what I can do to prevent the memory from climbing uncontrollably.

In general I want to know if this a good approach in the first place. I want to display custom drawn images inside a wpf app and be able to do so quickly (IE. a decent frame rate)

Is there a more native way to do this inside the WPF framework? Should I ditch WPF and go back to windows forms where I can control things more precisely?


回答1:


Solved. The problem was solved by using DeleteObject to clean up the instance of the hbitmap. Please refer to WPF CreateBitmapSourceFromHBitmap() memory leak for more details.



来源:https://stackoverflow.com/questions/1541381/wpf-with-gdi-memory-growth

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