Monday, September 8, 2008

Static Events Don't Release

Did you know that static events hold onto Handlers even after the Handler object is destroyed? This produces some crazy results when you have normal objects being created/destroyed but relying on the static event. You will get one call per object handle registered, even after they are destroyed.

Scenario:

SomeType Object1;
staticEvent1 += Object1.Handler(); //Sub object 1
Object1.Dispose(); //Destroy object 1
SomeType Object2;
staticEvent1 += Object2.Handler(); // Sub object 2
raisestaticEvent1(); // Raise the event

This produces an unexpected two calls to Object2.Handler.

The only solution is to make sure Object1 is unregistered when disposed, or better yet, don't use static events. There is no way to check which Handlers exist on a given event either, so you have to manually track the process.

0 comments: