In XNA, what is the best method to dispose of textures I no longer need?

本小妞迷上赌 提交于 2019-12-01 23:32:00
Andrew Russell

OK, first a bit of background: ContentManager caches loaded objects. There's a more detailed description here (or here). But basically each ContentManager owns everything it loads. You should not call Dispose on that content. The only way to clean it up is to unload everything in the cache with ContentManager.Unload (or Dispose).

I'm guessing that the issue you're having is that you've tried to Load a texture that you've previously called Dispose on - and are then attempting to use that disposed texture.

Although I suppose you could also run out of memory because the ContentManager is storing all those (empty, disposed) Texture2D objects, preventing the garbage collector from reclaiming them (see this answer).

So, if you want to go down this route, you need to modify the caching policy of ContentManager. How to do this is explained in this blog post. But basically you inherit from ContentManager, override Load, and call ReadAsset when you want to create a new instance of an asset from a content file.

The simplest thing to do would be to disable caching entirely, and that blog post has an example of exactly that. Then you can simply manually manage the lifetime of everything that content manager loads (i.e.: call Dispose on it yourself).

If you want something a bit more sophisticated, perhaps look at the design I propose in this answer, over on the GameDev site.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!