Question

Variables of my class:

protected List<Texture2D> textures_ = new List<Texture2D>();
protected Color fill_color_ = Color.White;

private int move_amount_ = 1;
private const int total_move_amount_ = 40;
private float current_move_amount_ = 0;
private bool moving_ = false;

protected static Random random_ = new Random();

protected Vector2 size_ = new Vector2(40.0f, 0);

Should I implement a Dispose method, or something to manage resources? In particular Texture2D objects?

Was it helpful?

Solution

Yes, you should implement a Dispose method, ideally through the IDisposable interface, in order to dispose of your Texture2D objects and other disposables.

What you do not need to implement is a finalizer (a method that will be called by the garbage collection in case you forget to call the dispose method), since you only have managed resources that implement their own finalizers in case they are not properly disposed.

The Texture2D objects will be disposed by the garbage collector eventually, should you not dispose of them yourself, but this has severe performance and memory drawbacks. Letting the garbage collection take care of this will considerably delay the clean up of these objects, and if you generate them fast enough may even crash your program.

There may be one exception: if you create only one or a few instances of your class, and keep these instances around until the termination of your program, you will probably not gain measurable benefits from implementing a dispose method. When your program is terminated, all these textures will be disposed of anyway. Disposing these objects manually is good practice nevertheless.

edit:
there may be some particular considerations regarding XNA resources that I am not well versed with; for that I would refer you to bubbinator's answer

OTHER TIPS

Since you are using XNA / MonoGame (Included due to the library's similarity) you only need to manually dispose of resources (via the Dispose method or using blocks) that do not come from the content pipeline.

For some quick reading on how to handle this sort of stuff try this.

Basically, if you pull the content from the pipeline, then call Content.Unload or divide the content between multiple ContentManagers.

On a side note, the tutorial I linked is actually a fairly active set of tutorials. However, there is only 1 person maintaining the site so things like Monogame tutorials are pushed onto the back burner in favor of java tutorials.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top