I have a rather large and complex game in C#, and in it are various monsters. The monsters are created in the game by a MonsterCreator, and each monster has various plugins that are loaded from external DLLs.
When my monsters die, they call a method in the MonsterCreator, and the MonsterCreator removes them from the game map, removes them from its own internal list of monsters, and then finally calls the Dispose() method on the monster itself.
The dispose method calls the dispose method of each plugin, then clears up any of its own code.
This seems to work fine, with lots of monsters, but somewhere there is a bug that crops up after a while, where a monster dies, but it has already been removed - it seems the callback telling the MonsterCreator is being called over and over, when the monster should have been removed on the first call.
The likely candidate is that some of the plugins for the monster register themselves with an Event that pulses them every X number of seconds so they can perform logic. Stepping through I can see that they are unregistering with the Event when they开发者_运维知识库 die, but something is getting through still and I don't know what it is.
Do you have any advice for debugging the problem? I can't post code really because it's split across a ton of libraries and plugin dlls, so it's more a case of figuring out the best way to debug it.
I threw an exception in code when the monster died callback method is thrown and the monster cannot be found on the map to be removed, so I have the misbehaviing Monster, is there a way I can see what is still linked to it?
You will need to use a profiler that will show you the connected graph. Something like the redgate ANTZ memory profiler.
Having said that, if you are using events, you need to be sure to un-register them. Failing to do so is the number one cause for memory leaks in .NET code, as the event is still referenced in the invocation list (and hence the object).
Beware that Dispose
doesn't remove the references that the other objects might have to your Monster
object! So the other objects referencing your Monster
can report that the Moster
dies after it had actually died.
Another popular source of mistakes is not unsubscribing from events: each subscribing to Monster
's events makes (implicitly) a reference to the Monster
instance.
精彩评论