
從HBitmap 建立WPF BitmapSource 時出現記憶體洩漏
使用CreateBitmapSourceFromHBitmap() 在WPF 中處理不當。當重複呼叫此方法而不釋放 BitmapSource 記憶體時,記憶體利用率持續增加。
根本原因
問題源自於 Bitmap.GetHbitmap( ) 擷取 GDI 位圖物件的句柄。 MSDN明確指出必須使用GDI的DeleteObject方法釋放該句柄,以釋放關聯的記憶體資源。
解決方案
要修復記憶體洩漏,釋放記憶體至關重要從 Bitmap.GetHbitmap() 取得的句柄。應進行以下修改:
範例程式碼
以下程式碼示範如何使用此方法:
// Import DeleteObject from gdi32.dll
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
// Your Code
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1000, 1000))
{
// Obtain HBitmap handle
IntPtr hBitmap = bmp.GetHbitmap();
try
{
// Create BitmapSource using HBitmap (using statement handles GDI bitmap disposal)
var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
// Release HBitmap handle
DeleteObject(hBitmap);
}
}透過實作這些變更,您可以有效防止記憶體洩漏並正確釋放與從HBitmap 建立的BitmapSource 關聯的資源。
以上是從 HBitmap 建立 WPF BitmapSource 時如何防止記憶體洩漏?的詳細內容。更多資訊請關注PHP中文網其他相關文章!