我面临一个问题,无法解决或在谷歌上找到解决方案。
我正在运行一个服务,加载或保存图像,并使用BitmapEncoder
或BitmapDecoder
类。一段时间后(取决于我保存/加载图像的频率),服务拒绝保存/加载图像。首先,在事件日志中看到警告:
堆分配失败
我搜索了它的含义,它与Windows服务拥有的GDI对象数量有限有关。可以修改注册表以增加这些对象的数量,但我认为这不是很好的解决方案,而且对我也没有用。
我的代码在保存时抛出以下异常和堆栈跟踪:
Error while storing image : System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
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.Threading.DispatcherObject..ctor()
at System.Windows.Media.Imaging.BitmapEncoder..ctor(Boolean isBuiltIn)
at Imaging.TiffReadWrite.Save(String filename, Image img)
当加载时
Error while loading image : System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
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.Threading.DispatcherObject..ctor()
at System.Windows.Media.Imaging.BitmapDecoder..ctor(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, Guid expectedClsId)
at Imaging.TiffReadWrite.Load(String filename)
我的代码用于保存图片,看起来像这样:
public static void Save(string filename, BitmapSource img)
{
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.None;
BitmapFrame frm = BitmapFrame.Create(img);
encoder.Frames.Add(frm);
encoder.Save(stream);
}
}
加载图片的代码如下:
public static BitmapSource Load(string filename)
{
BitmapSource resultImage = null;
using (Stream imSource = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var decoder = new TiffBitmapDecoder(imSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
resultImage = decoder.Frames[0];
}
return resultImage;
}
因此,服务拒绝保存/加载图像。我可以尝试捕获这个异常,以便服务可以继续运行,但是没有图片可以被保存/加载。有时在第一次出现这个异常后,几张图片可以被保存/加载,过了一会儿就不再执行保存/加载操作。
我唯一的解决方法是不在服务中运行此代码,而是在应用程序中运行。然后它运行得非常好,但这不是我要寻找的解决方案。如果有更好的建议,请告诉我。
有一些类似的帖子(异常的堆栈跟踪或多或少相同),实际上并没有解决: