2011-12-29 30 views
7

BitmapSource kullanan bir WPF uygulaması kullanıyorum ama bazı manipülasyon kullanmam gerekiyor, ancak bazı System.Drawing.Bitmaps işlemlerini yapmam gerekiyor.Yönetilmeyen Bellek sızıntısı

Uygulamanın bellek kullanımı, çalışırken artar.

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) 
{ 
      BitmapSource bms; 
      IntPtr hBitmap = bitmap.GetHbitmap(); 
      BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions(); 
      bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions); 
      bms.Freeze(); 
      return bms; 
} 

Ben düzgün bertaraf ediliyor yönetilmeyen bellek olduğunu varsayalım, ama yine elle yapmanın bulmak gibi olamaz:

Ben bu koda bellek sızıntısı aşağı daralmış var. Herhangi bir yardım için şimdiden teşekkür ederiz!

Alex

+0

olası yinelenen [WPF CreateBitmapSourceFromHBitmap bellek sızıntısı] (http://stackoverflow.com/questions/1546091/wpf-createbitmapsourcefromhbitmap-memory-leak) – Pieniadz

cevap

9

Sen hBitmap üzerinde DeleteObject(...) çağırmanız gerekir. Bkz: http://msdn.microsoft.com/en-us/library/1dz311e4.aspx

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) 
{ 
    BitmapSource bms; 
    IntPtr hBitmap = bitmap.GetHbitmap(); 
    BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions(); 
    bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, 
     IntPtr.Zero, Int32Rect.Empty, sizeOptions); 
    bms.Freeze(); 

    // NEW: 
    DeleteObject(hBitmap); 

    return bms; 
} 
+3

Ben tam olarak aynı cevabı yazmak üzereyken;) İşte "DeleteObject" yönteminin bildirimi: '[DllImport (" gdi32.dll ")] statik dışsal bool DeleteObject (IntPtr hObject); – ken2k

+0

@ ken2k: ve tam olarak aynı bildirimi eklemek üzereydik. Teşekkürler! – MusiGenesis

+0

Çok teşekkürler, bu benim problemimi çözüyor! – aforward

4

Sen HBITMAP DeleteObject(hBitmap) çağırmanız gerekir:

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) { 
     BitmapSource bms; 
     IntPtr hBitmap = bitmap.GetHbitmap(); 
     BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions(); 
     try { 
      bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions); 
      bms.Freeze(); 
     } finally { 
      DeleteObject(hBitmap); 
     } 
     return bms; 
} 
0

Bitmap tanıtıcıyı bırakıyor musunuz? MSDN'den GDI bitmap nesnesi tarafından kullanılan bellek boşaltmak için GDI NesneSil yöntemini çağırarak sorumludur

(http://msdn.microsoft.com/en-us/library/1dz311e4.aspx) göre

. GDI bitmap'leri hakkında daha fazla bilgi için, bkz. Windows GDI belgelerinde Bitmapler.

ait