What in this code causes memory leak in C#? -


in windows task manager discovered memory usage of program increases on time while it's running. memory leak caused code below. code loop iterating on list of images , resizes them according code example in msdn. resources seem managed , freed .dispose().

foreach ( string file in files ) {     image = image.fromfile( file );      rectangle croprect = new rectangle( 0, 0, 1000, 1000 );     bitmap src = ( bitmap ) image;     bitmap target = new bitmap( croprect.width, croprect.height );      using ( graphics g = graphics.fromimage( target ) )       {         g.drawimage( src, new rectangle( 0, 0, target.width, target.height ),                                         croprect,                                         graphicsunit.pixel );     }      image.dispose();     image = image.fromhbitmap( target.gethbitmap() );     src.dispose();     target.dispose();     image.dispose(); } 

could advise please can cause of memory leak in code?

from docs of gethbitmap:

you responsible calling gdi deleteobject method free memory used gdi bitmap object. more information gdi bitmaps, see bitmaps in windows gdi documentation.

then, docs of fromhbitmap:

the fromhbitmap method makes copy of gdi bitmap; can release incoming gdi bitmap using gdi deleteobject method after creating new image.

seems pretty clear... need call deleteobject:

[dllimport("gdi32.dll")] private static extern bool deleteobject(intptr hobject); 

as sjoshi points out, should use using blocks ensure dispose called in case of exception. deleteobject call should inside finally block same effect.


Comments

Popular posts from this blog

SQL php on different pages to Insert (mysqli) -

php - How can an email be returned from Stripe Checkout? -

sql - Partition elimination in Greenplum -