我正在尝试将一些图片复制到RAM,但这导致内存不足异常。我不知道为什么,但我认为这是"freeze()“的原因。但是如何“解冻”,这真的是问题所在吗?
public void preLoadThread(Object o)
{
Overlay ov = (Overlay)o;
ImageSource tempNext = BitmapConverter(ov.tempPreLoadPathNext);
ImageSource tempPrev = BitmapConverter(ov.tempPreLoadPathPrev);
tempNext.Freeze();
tempPrev.Freeze();
ov.Dispatcher.Invoke(
DispatcherPriority.Normal,
(Action)delegate()
{
ov.preLoadedNext = tempNext;
ov.preLoadedPrev = tempPrev;
ov.preLoadPathNext = ov.tempPreLoadPathNext;
ov.preLoadPathPrev = ov.tempPreLoadPathPrev;
}
);
}
public BitmapSource BitmapConverter(String path)
{
System.Drawing.Bitmap b = null;
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
{
try
{
b = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(fs);
}
catch (Exception)
{
GC.Collect();
GC.WaitForFullGCComplete();
}
fs.Close();
}
if ( b == null)
{
// Error
return null;
}
BitmapSizeOptions options = BitmapSizeOptions.FromEmptyOptions();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
b.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
options);
}
catch (Exception)
{
GC.Collect();
GC.WaitForFullGCComplete();
}
return bs;
}发布于 2010-12-08 05:57:40
我真心怀疑内存异常是否来自Freeze()调用,因为它实际上并没有分配任何内存。
我很确定你有一个GDI漏洞...在调用CreateBitmapSourceFromHBitmap()之后,必须在创建的位图上调用DeleteObject ...但是因为您调用的是GetHbitmap()作为参数,所以没有要删除的句柄。
试试这个:
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
...
IntPtr hObject = b.GetHbitmap();
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hObject,
IntPtr.Zero,
Int32Rect.Empty,
options);
DeleteObject(hObject);亨克是对的,你不应该强迫GC收集...它对您没有真正的帮助,因为您并没有真正释放要收集的任何东西(您要释放的唯一东西必须通过DeleteObject()来清理。
我们谈论的是多少张1378x2000的图像?即使你修复了你的GDI漏洞,这些都是很大的图片,很快就会消耗掉内存。
柯蒂斯克是对的你不能解冻你必须克隆..。但是当您这样做时,您将分配内存。只是想提醒你。
我想在64位下运行不是一个选择...
发布于 2010-12-08 04:34:26
至于你的“解冻”问题,你不能在最初的项目上,但你可以剥离一个解冻的克隆,details and example at MSDN
https://stackoverflow.com/questions/4381072
复制相似问题