I have am using a WPF application which uses BitmapSource but I need to do some manipulation but I need to do some manipulation of System.Drawing.Bitmaps.
The memory use of the application increases while it runs.
I have narrowed down the memory leak to this code:
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;
}
I assume it is the unmanaged memory not being disposed of properly, but I cannot seem to find anyway of doing it manually. Thanks in advance for any help!
Alex
Unmanaged memory: memory allocated outside of the managed heap and not managed by Garbage Collector. Generally, this is the memory required by . NET CLR, dynamic libraries, graphics buffer (especially large for WPF apps that intensively use graphics), and so on. This part of memory cannot be analyzed in the profiler.
In most cases, you can fix the Windows 10 memory leak issues yourself. You can close resource-intensive apps, disable certain startup apps, and perform similar tasks to fix a memory leak.
DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.
A memory leak reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly due to thrashing.
You need to call DeleteObject(...)
on your hBitmap
. See: 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;
}
You need to call DeleteObject(hBitmap)
on the hBitmap:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With