2010-01-05 18 views
6

我不久前發佈了一個問題,這個問題不久前我的程序基本上正在泄漏內存:請參閱here。我現在已經專門跟蹤了一些代碼,我將Bitmap對象的原始字節複製到託管數組中。相關代碼:將Marshal.Copy從原始位圖數據安全使用到託管數組

public class FastBitmap 
{ 
    ... 
    private byte[] rgbValues; 
    private int height; 
    private int width; 
    private Bitmap image; 

    public FastBitmap(Bitmap plainBitmap) 
    { 
     width = plainBitmap.Width; 
     height = plainBitmap.Height; 
     image = new Bitmap(plainBitmap); 
     LockPixels(new Rectangle(0, 0, image.Width, image.Height)); 
    } 

    private void LockPixels(Rectangle area) 
    { 
     if (locked) 
      return; 
     locked = true; 
     BitmapData bitmapData = image.LockBits(area, ImageLockMode.ReadWrite, 
           PixelFormat.Format24bppRgb); 
     IntPtr ptr = bitmapData.Scan0; 
     int stride = bitmapData.Stride; 
     int numBytes = image.Width * image.Height * 3; 
     rgbValues = new byte[numBytes]; 
     for (int r = 0; r < image.Height; ++r) 
     Marshal.Copy(new IntPtr((int)ptr + stride * r), 
          rgbValues, image.Width * 3 * r, image.Width * 3); 
    } 
} 

因此多數民衆贊成,這是造成內存不被回收的代碼的所有程度,我想這事做與Marshal.Copy()雖然我曾以爲,因爲我是從一個位圖(自行清理?)複製到一個託管陣列,沒有問題。

所以問題:是否有必要通過IDisposable接口或類似的東西來清理Bitmap對象。在這種情況下使用Marshal.Copy()會有什麼(如果有的話)本質上是錯誤的,我可以在哪裏清理問題?

謝謝

只要你知道我已經測試了下面的代碼,以驗證它確實是這個問題引起:

Bitmap bmp = new Bitmap(1000, 1000); 
for (int n = 0; n < 100; ++n) 
{ 
    FastBitmap fb = new FastBitmap(bmp); 
} 

開始和這個序列的整體記憶的結束無論您等待多長時間,使用量都會增加320mb,並且不會消失。

回答

8

您忘記了調用image.UnlockBits(bitmapData);

+1

非常感謝,幾個小時的沮喪和它那麼簡單。 – DeusAduro 2010-01-05 09:44:22

+0

看起來你錯過了第二個代碼片斷,這個文章中的'UnlockBitmap'函數(它調用'UnlockBits'):http://www.devx.com/webdev/Article/44658/1763/page/2 – rwong 2012-07-12 15:55:26

相關問題