2014-10-06 48 views
0

我注意到我的程序泄漏內存。所以我用dotMemory找到泄漏,並且看起來這是造成泄漏的功能:內存泄漏時元帥。複製

private void LoadBits() 
    { 
     // Lock the bitmap's bits. 
     Rectangle rect = new Rectangle(0, 0, bm.Width, bm.Height); 
     bmpData = bm.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bm.PixelFormat); 
     stride = bmpData.Stride; 

     // Get the address of the first line. 
     IntPtr ptr = bmpData.Scan0; 

     // Declare an array to hold the bytes of the bitmap. 
     byteCount = Math.Abs(bmpData.Stride) * bm.Height; 
     bytes = new byte[byteCount]; 

     // Copy the RGB values into the array. 
     System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, byteCount); 
    } 

這我怎麼解鎖位。

private void SaveBits() 
    { 
     // Update Stuff 
     IntPtr ptr = bmpData.Scan0; 

     System.Runtime.InteropServices.Marshal.Copy(bytes, 0, ptr, byteCount); 
     bm.UnlockBits(bmpData); 
    } 

我實現了這個類的IDisposable接口。我在那裏調用SaveBits,所以即使我忘記調用SaveBits,GC也應該爲我做。 是的,我確實調用了bm.Dispose()並將Dispose方法中的所有內容都設置爲null。

+1

LoadBits和SaveBits使用不同的變量。一個是'_bm',另一個是'bm',你可以在錯誤的對象上解鎖位嗎?也可以在調用SaveBits()之前多次調用LoadBits(),這也會導致內存泄漏。嘗試在'SaveBits()'末尾放置'bmpData = null',並在'LoadBits()'的開始處放置if(bmpData!= null)拋出新的InvalidOperationException();並查看是否引發異常。 – 2014-10-06 23:11:38

+0

我發佈了問題後重構了。所以「LoadBits」顯示了舊的var名稱。允許我更新它。 – Trauer 2014-10-06 23:24:19

+1

如果你做空檢查並拋出異常,它不會拋出? – 2014-10-06 23:25:43

回答

2

完成後您需要UnlockBits()

+0

我已經這樣做了。沒有幫助。 – Trauer 2014-10-06 22:40:59