When do I need to use dispose() on graphics?

lala picture lala · Jul 3, 2010 · Viewed 9.9k times · Source

I'm learning to draw stuff in C# and I keep seeing recommendations to use dispose(), but I don't quite understand what it does.

  • When should I be using dispose() on a code-drawn graphic?
  • What happens if I don't?
  • Do I need to call it every time a graphic is not visible, such as on a GUI that has tabs and the user switched to the other tab, and then redraw it when they switch back?
  • Will I break things if I call it when I shouldn't?
  • Will Batman escape the evil clutches of the Joker?

Answer

Stephen Cleary picture Stephen Cleary · Jul 3, 2010
  • When should I be using dispose() on a code-drawn graphic? Whenever you are completely done with any object that implements IDisposable, you should call Dispose just before it becomes eligible for garbage collection. As others have pointed out, it's best to use the using statement instead of calling Dispose directly.
  • What happens if I don't? Your program will be slightly less efficient because it will take up slightly more resources than necessary. This is the only drawback to not disposing graphics; however, not disposing other classes can actually cause errors (one famous example is StreamWriter). For this reason, it's best to always dispose any class that implements IDisposable, as a general rule.
  • Do I need to call it every time a graphic is not visible, such as on a GUI that has tabs and the user switched to the other tab, and then redraw it when they switch back? No. Objects should only be disposed when you are completely done with them.
  • Will I break things if I call it when I shouldn't? Yes. If you call Dispose before you are done with the object, and then attempt to use the disposed object, you will get an ObjectDisposedException.
  • Will Batman escape the evil clutches of the Joker? Tune in tomorrow, same bat-time, same bat-channel!