WPF: Memory leak in CreateBitmapSourceFromHBitmap()
In WPF applications, repeated use of CreateBitmapSourceFromHBitmap()
can cause memory leaks. This problem occurs because the underlying GDI bitmap used by CreateBitmapSourceFromHBitmap()
is not released correctly.
To resolve this memory leak, the GDI bitmap must be released manually using the gdi32.dll
method in the DeleteObject()
library. You can achieve this by wrapping the Bitmap
object in a using()
statement, which automatically calls the Dispose()
method to release the GDI bitmap. Here is the updated code:
<code class="language-csharp">using System.Runtime.InteropServices; ... using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1000, 1000)) { IntPtr hBitmap = bmp.GetHbitmap(); try { var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(hBitmap); } }</code>
You can free a GDI bitmap and prevent memory leaks by using the using
statement and calling DeleteObject()
explicitly. This ensures that memory is released correctly even if called repeatedly.
The above is the detailed content of WPF: How to Prevent Memory Leaks When Using CreateBitmapSourceFromHBitmap()?. For more information, please follow other related articles on the PHP Chinese website!