Anonymous Delegate Hell

Published 15 February 07 10:56 AM | adrian

Be careful when you're using anonymous delegate to handle external events. Anonymous delegate event handler are not unsubscribable... That means once you define it, it sticks around, even after the original object is destroyed. Take a look at the attached program.

The event is published from a static class Publisher. Client would call RaiseEvent() method to initiate the event.

Subscriber to the event are three classes, SubscriberA (using anonymous delegates), SubscriberANonAnonymous (using standard event handling delegate), and SubscriberANonAnonymousWithIDisposable (using standard event handling delegate plus IDisposable implementation to be used with using statement for explicit destruction). Each class will write a line to the console. The expected result was no line written, since disposed objects shouldn't handle events.

The fact: only SubscriberANonAnonymousWithIDisposable that does not write a line.

This problem does not happen when you use anonymous delegate to handle internal events, since the publisher most likely be gone in the process of destruction. An example of this would be handling of Button.Click event inside a Windows Form.

P.S.: To use the attached file, first create an empty Console Application Project, then copy paste the content of the file to the Program.cs.

Share this post: | | | |
Filed under:

Comments

No Comments