c# - Dispose works fine, but not on terminating -



c# - Dispose works fine, but not on terminating -

i have class implements idisposable, because uses image resources (bitmap class) gdi+. utilize wrapping gimmicky lockbits/unlockbits. , works fine, when phone call dispose() or using statement.

however, if leave programme terminate without disposing, system.accessviolationexception. intuitively, think gc phone call dispose same way do, , object gracefully release resources, that's not happening. why?

here's idisposable code:

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 unlockbits bytes = null; // byte[] of image bmpdata = null; // bitmapdata object if (safedispose && bm != null) { bm.dispose(); // bitmap object bm = null; } _disposing = true; }

here's when works ok:

using (var qbm = new quickbitmap("myfile.jpg")) { // utilize qbm.getpixel/qbm.setpixel @ }

here's when doesn't work:

public static void main (string[] args) { // example, constructing object , doing nil throw exception var qbm = new quickbitmap(args[0]); qbm.setpixel(0, 0, color.black); qbm.save(); }

the finish excetion (there's no inner exception):

an unhandled exception of type 'system.accessviolationexception' occurred in mscorlib.dll additional information: attempted read or write protected memory. indication other memory corrupt.

the reproduction 100%, on different machines. figure out should utilize using or dispose(), not using bad , stuff. want know: why happen? why memory "protected"? kind of access violating?

the problem occurs because included unnecessary finalizer in implementation. code executed finalizer generally cannot access managed objects safely. phone call savebits results in utilize of managed objects in violation of rule, though did not include code method.

the best solution remove finalizer quickbitmap, since quickbitmap class not directly own unmanaged resources.

c# gdi+

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -