Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Why you need to remove event handler for XNA?

0.00/5 (No votes)
26 Jul 2012 1  
Why you need to remove event handler for XNA?

Title appears to be a nonsense

Okay, when you added the event, you need to remove them. Let’s look at these code below:

private void quitted ( object sender, EventArgs e )
{ Console.Write ( "I quit" );  }

Student tom = new Student ( );
tom.Quitted += new EventHandler ( this.quitted );

tom.Quitted -= new EventHandler ( this.quitted );

We added a Quitted event for student, and then, we remove this event. If the instance tom do not remove Quitted event, what will happen? To be honest, I don’t know, but one thing to determine is if you have a lot of tom like this, then, it will result memory leak, eventually leads to a exception.

WinForm

If it is a WinForm program, you added a Click event for a button, you don’t need to remove it when the window is destroyed, I think perhaps is for the convenience of the programmers, these this job already performed by .NET or Visual Studio.

XNA

XNA is actually simple, and a lot of work you need to finish them by yourself, especially the events of Sprite in the game, because the game itself is constituted by a large number of the Sprites, they are constantly created and destroyed.So, if you do not remove events of Sprites, the game will be over (not because the player is dead, but game crashes).

I actually ran into this problem (OK, I was stupid), no matter how to try, the game always throws a exception for a limited period of time.Fortunately, friends reminded me that I should remove the events, the problem is finally solved.

Make sure that the code is called

If you added event for an instance in a method of a class, then in the other methods in this class, you should remove the event for this instance, and then make sure the method is called.

private Student one = new Student ( );

public School ( )
{ this.one.Quitted += ...; }

public void End ( )
{ this.one.Quitted -= ...; }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here