# When to Dispose Textures

I recently realized Texture2D implements IDisposable, and now (while trying to track down a memory leak) wonder about where and when I should dipose this.

My current architecture is that I have a SpriteComponent instance which encapsulates and hides the Texture2D. Internally, when I switch screens (eg. MainMenuScreen => WorldMapScreen), I call Dispose on the current screen, which calls dispose on the entities, which calls dispose on the textures.

But this results in some wacked-out behaviour, like textures apprearing super zoomed in momentarily, or appearing black, or appearing as garbage image data.

So my question is really, when should I call Dispose on Texture2Ds?

(FYI, I also can switch to a screen, and then later switch back to it, which currently causes me to reload the sprites, and by proxy, the textures.)

• – ashes999 Jan 22 '13 at 14:13
• The related link you just posted is pretty important. You don't say how you are loading these textures - the correct answer depends on how they are loaded! – Andrew Russell Jan 23 '13 at 7:09
• @AndrewRussell I'm loading them with a standard content manager, which I use for all my content. – ashes999 Jan 23 '13 at 11:40
• Well, in that case, as I'm sure you know from that link, you shouldn't Dispose them at all ;) You have to unload the whole ContentManager so it will also stop caching the disposed instances. – Andrew Russell Jan 24 '13 at 5:24

• Do you mean that textures should live forever, and only be disposed if they won't be loaded again for that game? To clarify, I'm not talking about unloading them from the content manager, but invoking Dispose on them. – ashes999 Jan 22 '13 at 17:28