2010-12-07 39 views
0

我想将一些图片复制到RAM,但这会导致内存不足例外。 我不知道为什么,但我认为这是“freeze() ”。但如何“解冻”,这真的是问题吗?内存不足异常C#freezable.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; 
    } 
+3

GC.Collect在catch块中不能作为答案。 – 2010-12-07 20:19:58

+0

我知道..这是尝试和错误,因为我不知道如何解决这个泄漏 – Martin 2010-12-07 20:25:35

回答

1

我真诚地相信记忆异常是从冻结到来( )调用,因为这实际上没有分配任何内存。

我敢肯定你有一个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泄漏,那些图片也很大,并且会很快耗尽内存。

Curtisk是正确的,你不能解冻,你必须克隆...但是当你这样做的时候你会分配内存。只是为了警告你。

我认为在64位下运行不是一种选择...