We have been going through a big memory leak analysis and have found one of the contributing factors has been the non removal of delegates on events causing objects to not be GCed quickly enough (or sometimes forever).
Would anyone have any ideas as to how to write a rule in FXCop to ensure that we have delegates are removed from handlers?
I've just seen this and as such I'll ask there for more information.
You need to be more specific. You don't need to check that ALL event delegates were unsubscribed, because in a common case a subscriber lives shorter life than a publisher. And a memory leak only happens when your subscriber appears to be longer-lived than a publisher, hence there is a reference, which prevent GC from collecting the publisher object.
Now we need to verify that if you subscribe to an event on a relatively short-living object, you unsubscribe from it eventually.
An heuristics I can come up with in this case: analyze all local-variable objects (that are scoped by the current code block {}) and all objects, which you explicitly Dispose. For every event on these objects count the number of times you subscribe to them and the number of times you unsubscribe. If the first number is greater then emit a warning.
Of course that doesn't cover all the cases, but I guess no static approach can cover all the cases in this problem, you need some method that is good enough.
I won't mention the advantages of dynamic analysis and code reviews here as it is a separate topic, not related to the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With