Preventing OutOfMemoryException with GC.AddMemoryPressure()?

前端 未结 2 1619
你的背包
你的背包 2020-12-15 07:05

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:

<
相关标签:
2条回答
  • 2020-12-15 07:30

    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.

    0 讨论(0)
  • 2020-12-15 07:46

    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.

    0 讨论(0)
提交回复
热议问题