Currently, I have to fix an existing Silverlight application that’s leaking a lot of memory. Using Redgate’s ANT profiler I managed to detect possible problems. One of them is a static class that wraps around a web service, which contains two event handlers to support an asynchronous calculation.
And you’ve guessed it… A lot of objects assign an event to this handler but most don’t release it again. As a result, those objects are linked to these static events and thus almost never released…
I need a simple fix to work around this problem. So, what possible options do I have to fix this memory leak without these changes having a lot of impact?
Making the event handlers non-static will result in a huge change, thus an undesired action…
Use the Weak Event pattern (don’t know if it’s possible with SL). This will allow a dirtier programming model with calling your static method.
A better alternative whould be to properly subscribe / unsubscribe events (agreeing with tomasmcguinness), but this implies you can change the calling code and/or ask the consumers to better develop.
Another solution could to use async patterns. Maybe waiting for a Callback delegate in your method call, or even better, return a Task object.