c# - .Net and Bitmap not automatically disposed by GC when there is no memory left -
i'm wondering how allocation , disposal of memory allocated bitmaps work in .net.
when lot of bitmap creations in loops in function , call in succession work until @ point bitmap wont able allocate memory giving exception "invalid parameter" size specified.
if call garbage collector while while works.
with following code able repoduce error:
class bitmapobject { public bool visible { { return enb; } set { enb = value; } } private bool enb; private bitmap bmp; public bitmapobject(int i, bool en) { enb = en; bmp = new bitmap(i, i); } } class pool<t> t : bitmapobject { list<t> preallocatedbitmaps = new list<t>(); public void fill() { random r = new random(); (int = 0; < 500; i++) { bitmapobject item = new bitmapobject(500, r.nextdouble() > 0.5); preallocatedbitmaps.add(item t); } } public ienumerable<t> objects { { foreach (t component in this.preallocatedbitmaps) { if (component.visible) { yield return (t)component; } } } } } static class program { /// <summary> /// main entry point application. /// </summary> [stathread] static void main() { (int = 0; < 10; i++ ) { test(); // without breaks //gc.collect(); //gc.waitforpendingfinalizers(); } console.readkey(); } private static void test() { pool<bitmapobject> pool = new pool<bitmapobject>(); pool.fill(); (int = 0; < 100; i++) { var visbitmaps = pool.objects; // } } }
the .net bitmap
class "encapsulates gdi+ bitmap", means should call dispose
on bitmap
when finished it,
"always call dispose before release last reference image. otherwise, resources using not freed until garbage collector calls image object's finalize method."
Comments
Post a Comment