Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any ideas on how to write a static analysis rule (FXCop) to ensure that event delegates are removed

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.

like image 440
Preet Sangha Avatar asked May 12 '09 20:05

Preet Sangha


1 Answers

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.

like image 163
Max Galkin Avatar answered Nov 19 '22 05:11

Max Galkin