Working in .Net 2.0, moving the code base to 4.0 soon
Recently I have been working with serializing classes with events, and finding my event subscribers (i.e. a Form) would attempt to serialize too (I am using [field:NonSerializable] now to stop this).
This got me to thinking, if I pass a delegate to a static class’s method (to be used method scope only), does the static class root the delegate’s owner, causing it to be uncollectable by GC?
I have a static ListUtilities class doing the job of lambda expressions, as well as static caches, that I regularly pass delegates, and wondering if this could be leaking memory?
No, nothing to worry about there. Passing a delegate to a method is fine, (unless that method stores the delegate somewhere indefinitely).
What is problematic, though is static events (or events on long-lived objects, such as singletons). If you don’t unsubscribe those, then the event can keep the object alive forever. For example:
now the static event on
MyUtilityprevents the newSomeTypeinstance from being collected until that event subscription is removed… which it probably never will be, since it is an anonymous method (which need voodoo to unsubscribe).