In our application we are exporting a lot of images and we ran into this Win32Exception:
System.ComponentModel.Win32Exception (0x80004005): Not enough storage is available to process this command
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Threading.Dispatcher..ctor()
at System.Windows.DependencyObject..ctor()
at System.Windows.Media.Imaging.BitmapSource..ctor(Boolean useVirtuals)
at System.Windows.Media.Imaging.CachedBitmap..ctor(Int32 pixelWidth, Int32 pixelHeight, Double dpiX, Double dpiY, PixelFormat pixelFormat, BitmapPalette palette, Array pixels, Int32 stride)
at System.Windows.Media.Imaging.BitmapSource.Create(Int32 pixelWidth, Int32 pixelHeight, Double dpiX, Double dpiY, PixelFormat pixelFormat, BitmapPalette palette, Array pixels, Int32 stride)
The problem is, that we create BitmapSource objects in different threads and there is a memory leak. If you execute this code, there are still a lot of objects in memory:
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 100; i++)
{
Thread t = new Thread(new ThreadStart(() =>
{
BitmapSource temp = BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgr24, null, new byte[3], 3);
temp.Freeze();
}));
t.Start();
threads.Add(t);
}
foreach (var thread in threads)
{
thread.Join();
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
We do this in a Windows service and after a few days the system crashes. With the "Not enough storage..."-Message. At this point a lot of other applications crash, you can't open up an editor or other Windows applications. Could it be, that the Desktop Heap is full? The memory doesn't go up much (160MB max) and the machine has 16GB of RAM.
How do we dispose the BitmapSource correctly?