I am developing a custom control, which internally subscribes to Touch.FrameReported - a static event. This has the potential to cause a memory leak (and in some case, it does).
This is my current solution. To subscribe / unsubscribe in the Loaded / Unloaded event. However, I'm finding that the Unloaded event is not always called. This can lead to memory leaks.
// Imagine this is a CustomControl, to be consumed by users
// with no regard for calling Dispose
public class CustomGrid : Grid
{
public CustomGrid()
{
Loaded += (s, a) =>
{
Touch.FrameReported -= OnTouchFrameReported;
Touch.FrameReported += OnTouchFrameReported;
};
Unloaded += (s, a) =>
{
// The intention is to unsubscribe on unload, which should pre-date
// user intended 'disposal' of the control
Touch.FrameReported -= OnTouchFrameReported;
};
}
Is there a known pattern to solve this? Unsubscribing to events in a Custom Control 'tear-down'? I have already tried:
- Unsubscribe in unloaded. Doesn't always get called.
- Dispose. Cannot be used because a user may not deterministically call Dispose
- Weak Events. Nice, but many implementations are unsuitable for WinRT/Silverlight, or, they require explicit deregistering, or, they only de-register if the event is called (Duh! Its a weak-event)!
- Finalizer. Doesn't Finalizer get prevented if there are GC roots like event handlers?