1

Possible Duplicate:
When is Dispose necessary?
.Net and Bitmap not automatically disposed by GC when there is no memory left

After a round of hair-pulling I finally figured out that my culprit was reallocating a Bitmap object in a resize operation. After enough reallocates the system quit trying to draw the bitmap (the Paint event wasn't being called) and got very jerky.

Disposing of the old bitmap before allocating the new one fixed it.

This says that there must be some underlying resource (beyond simply memory) being used up by orphaning those old bitmaps.

I thought bitmaps were just chunks of memory that I could leave for the garbage collector. What's going on??

Community
  • 1
  • 1
Loren Pechtel
  • 8,945
  • 3
  • 33
  • 45
  • 1
    The question is: is an `IDisposable` interface involved? If so, correct code *must* invoke `Dispose` on it, as it says "hey, this implementations may or may not need to clean something up in a timely manner before a finalizer is guaranteed to run". –  Sep 26 '12 at 05:22
  • 1
    See [When is `Dispose` necessary](http://stackoverflow.com/questions/1209585/when-is-dispose-necessary), [Bitmap not automatically disposed by GC](http://stackoverflow.com/questions/5838608/net-and-bitmap-not-automatically-disposed-by-gc-when-there-is-no-memory-left), [Proper use of the `IDisposable` interface](http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface), many others. – verdesmarald Sep 26 '12 at 05:30
  • @verdesmarald: I guess I phrased the search wrong. – Loren Pechtel Sep 26 '12 at 16:26

1 Answers1

4

The MSDN states that Bitmap encapsulates a GDI+ object. So I would expect that you have to call Dispose() to release these system resources when you no longer need them.

EDIT: Bitmap being a subclass of Image, the following MSDN statement applies

Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.

  • Yes. If you open Task Manager and go to the Processes tab (I don't know about Windows 8) and enable the "GDI Objects" column, you'll see what happens when you don't dispose of `Bitmap` objects. – Dai Sep 26 '12 at 05:26