C# Bitmap/Graphics Out of Memory -
i'm trying take snapshot of whole screen reading pixel values. i'm doing without problem. after 214 snapshots, i'm getting out of memory exception.
bitmap screenshot = new bitmap(screen.primaryscreen.bounds.width, screen.primaryscreen.bounds.height); public bitmap takesnapshot() { graphics graphic = null; rectangle rect = new rectangle(0, 0, screen.primaryscreen.bounds.width, screen.primaryscreen.bounds.height); using (graphic = graphics.fromimage(screenshot)) { graphic.copyfromscreen(screen.primaryscreen.bounds.x, screen.primaryscreen.bounds.y, 0, 0, screenshot.size, copypixeloperation.sourcecopy); } return screenshot.clone(rect,system.drawing.imaging.pixelformat.format32bppargb); }
i'm using method timer
bitmap bmp = takesnapshot(); var c = bmp.getpixel(0,0);
it giving invalid parameter exception. solved "using". i'm stuck on exception.
you need dispose disposable resources once you're done working them. bitmap
class implements idisposable
- disposable resource. correct pattern instead of
bitmap bmp = takesnapshot(); var c = bmp.getpixel(0,0);
something like
bitmap bmp = null; try { bmp = takesnapshot(); var c = bmp.getpixel(0,0); // more work bmp } { if (bmp != null) { bmp.dipose(); } }
or in short form (which preferable):
using(bitmap bmp = takesnapshot()) { var c = bmp.getpixel(0,0); // more work bmp }
reference: using objects implement idisposable
edit
you can emulate issue:
public class testdispose : idisposable { private intptr m_chunk; private int m_counter; private static int s_counter; public testdispose() { m_counter = s_counter++; // 256 mb m_chunk = marshal.allochglobal(1024 * 1024 * 256); debug.writeline("testdispose {0} constructor called.", m_counter); } public void dispose() { debug.writeline("testdispose {0} dispose called.", m_counter); marshal.freehglobal(m_chunk); m_chunk = intptr.zero; } } class program { static void main(string[] args) { for(var = 0; < 1000; ++) { var foo = new testdispose(); } console.writeline("press key end..."); console.in.readline(); } }
Comments
Post a Comment