For the specific question "Will pClass be garbage collected": the event subscription has no effect on the collection of pClass (as the publisher).
For GC in general (in particular, the target): it depends whether MyFunction is static or instance-based.
A delegate (such as an event subscription) to an instance method includes a reference to the instance. So yes, an event subscription will prevent GC. However, as soon as the object publishing the event (pClass above) is eligible for collection, this ceases to be a problem.
Note that this is one-way; i.e. if we have:
publisher.SomeEvent += target.SomeHandler;
then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.
So no: if pClass is going to be collected anyway, there is no need to unsubscribe the listeners. However, if pClass was long-lived (longer than the instance with MyFunction), then pClass could keep that instance alive, so it would be necessary to unsubscribe if you want the target to be collected.
Static events, however, for this reason, are very dangerous when used with instance-based handlers.
Thanks for the feedback guys. I'll go along with your advice and let the system take of care of what the system was designed to take care of!
I actually have since found a good answer to my question in a book I have on the .NET framework. It says:
The whole purpose of the .NET garbage
collector is to manage memory on our
behalf. However, in some very rare
circumstances, it may be beneficial to
programmatically force a garbage
- When your application is about to enter into a block of code that you don't
want interrupted by a possible garbage
- When your application has just finished allocating an extremely large number
of objects and you wish to remove as
much of the acquired memory as soon as
When you have your XAML pages displayed, are you registering for keyboard events? If so, are you forgetting to unregister from keyboard events when you remove those pages from the screen?
Since there is no "Unloading"-like event on either the UserControl or Page class in Silverlight (at least that I know of), what I do is have my pages implement a interface I define that contains a single method like "Cleanup" or "Close". Before I remove the control from the screen, I call Cleanup() on the control and have it do things like unregister from events it may have registered.
If you don't unregister from events the page's object will never be garbage collected because the CLR thinks the object is still live.