我需要逐个像素地绘制图像并将其显示在WPF中.我试图通过使用System.Drawing.Bitmap然后使用CreateBitmapSourceFromHBitmap()创建BitmapSource一个WPF图像控件来做到这一点.我在某处有内存泄漏,因为当CreateBitmapSourceFromBitmap()重复调用时,内存使用率会上升,并且在应用程序结束之前不会下降.如果我不打电话CreateBitmapSourceFromBitmap(),内存使用量没有明显变化.
for (int i = 0; i < 100; i++)
{
var bmp = new System.Drawing.Bitmap(1000, 1000);
var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
source = null;
bmp.Dispose();
bmp = null;
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能释放BitmapSource记忆?
我无法理解这里泄漏的是什么
using GDI = System.Drawing;
public partial class MainWindow : Window
{
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr obj);
public MainWindow()
{
InitializeComponent();
var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(50) };
timer.Tick += (s, a) =>
{
using (var bitmap = new GDI.Bitmap(1000, 1000))
{
var hbitmap = bitmap.GetHbitmap();
var image = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
image.Freeze();
DeleteObject(hbitmap);
}
};
timer.Start();
}
Run Code Online (Sandbox Code Playgroud)
bitmap?弃置.hbitmap?删除.image?冷冻,但事实并非如此IDisposable.
事实是,这个应用程序会崩溃(在运行约20秒后在我的电脑上)
System.Drawing.dll中发生了未处理的"System.OutOfMemoryException"类型异常
附加信息:内存不足.
有任何想法吗?