我有一個類實現IDisposable
,因爲它使用來自GDI +的圖像資源(Bitmap
類)。我用它來包裝所有那些噱頭LockBits
/UnlockBits
。它可以正常工作,無論是我撥打Dispose()
還是using
聲明。配置工作正常,但沒有終止
但是,如果我離開程序終止而不處置,我得到一個System.AccessViolationException
。直覺上,我認爲GC會像我一樣調用Dispose
,並且對象會優雅地釋放資源,但這不是發生的事情。爲什麼?
這裏的IDisposable
代碼:
private bool _disposing = false;
~QuickBitmap() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool safeDispose) {
if (_disposing)
return;
SaveBits(); // private wrapper to UnlockBits
bytes = null; // byte[] of the image
bmpData = null; // BitmapData object
if (safeDispose && bm != null) {
bm.Dispose(); // Bitmap object
bm = null;
}
_disposing = true;
}
這裏的,當它工作的很好:
using (var qbm = new QuickBitmap("myfile.jpg"))
{
// use qbm.GetPixel/qbm.SetPixel at will
}
這裏的時候它不工作:
public static void Main (string[] args) {
// this is just an example, simply constructing the object and doing nothing will throw the exception
var qbm = new QuickBitmap(args[0]);
qbm.SetPixel(0, 0, Color.Black);
qbm.Save();
}
完整EXCETION是(有沒有內部異常):
An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
再現100%,甚至在不同的機器上。我弄清楚我們應該使用using
或Dispose()
,不使用它是壞的和所有的東西。我只想知道:爲什麼會發生這種情況?爲什麼內存「受保護」?我違反了哪種訪問方式?
只是好奇......你爲什麼認爲'LockBits'是「噱頭」? – 2014-10-08 17:39:59
@EdS。因爲它需要我繼續使用'IntPtr'。我使用這個類來避免在更高級的類中使用'IntPtr'。 – Mephy 2014-10-08 17:40:59
你沒有遵循規定的Dispose模式。 – 2014-10-08 17:41:51