I\'m currently debugging a method we use to tag images with a certain text before displaying them in our system.
The tag method looks like this at the moment:
<If you are looking for a way to ensure you'll have enough memory available for an operation, use MemoryFailPoint
.
With this, through a using
, you can define a region in which you will need a certain amount of memory. If that isn't available, it will throw a recoverable InsufficientMemoryException
.
See http://msdn.microsoft.com/en-us/library/system.runtime.memoryfailpoint.aspx for more information.
You are having a different problem here, this code uses very little memory. Sadly GDI+ exceptions are pretty crummy. Diagnose this with TaskMgr.exe, Processes tab. View + Select Columns and tick GDI Objects, Handles and USER Objects.
If my suspicion is correct, you'll see the GDI Objects counter for your process climbing constantly as this code runs. When it reaches 10,000 Windows decides that there's something fundamentally wrong with the code and refuses to create any more handles. GDI+ then gets a bit gimpy about it and reports an out of memory error. Wrong, it should have been a 'could not create handle' error. An error code that it doesn't have. .NET is powerless to improve the exception.
Anyhoo, the reason is that you are not calling Dispose() on the font and brush. Wrap them with the using statement. This normally doesn't cause trouble but your program is apparently using too little garbage collected memory to ever kick off the finalizer thread.