I’m fixing a User control component using the .NET 1.1 framework.
There are many instances of this user control referencing a singleton wrapping a COM resource.
They subscribe to events from this resource.
I suspect that the reason why we are having a degrading performance is because the singleton is maintaining a reference to the user control classes even after their respective windows are gone. Thus preventing GC.
They unsubscribe the event in their finalize method.
Hence I suspect a chicken and egg problem. The finalize wont execute because they are being referenced through their event subscription in the longer lived Singleton, preventing GC.
Where in a User Control should I perform the event unsubscribe to make it eligible for GC?
I do not own the application hosting the user control.
You should unsubscribe when the control is disposed, really. If you can’t easily modify the
Disposemethod yourself, you could add an event handler to theDisposedevent:If you want to subscribe to events using anonymous methods or lambda expressions, you’ll need to use a separate local variable so that you can refer to it again:
An alternative is to use “weak event handlers” – there are many articles about this on the web; here’s one which goes into a fair amount of detail.