You need to be careful about using event handler for NetworkChange

Actually the issue I am discussing here is in general true for any event handler. .net event handler are strong reference. In case of NetworkChange it become more important because both event handler on NetworkChange object are static handlers, so there life time is the lifetime of the process.

For example you may be using code like below for registering an instace method of your object as handler

NetworkAvailabilityChangedEventHandler myHandler = new NetworkAvailabilityChangedEventHandler (myNetworkAvailabilityChangeHandler);
NetworkChange.NetworkAvailabilityChanged += myHandler;

Then you should make sure to unregister event handler once you are done with this object, otherwise your object is not garbage and you will see a memory leak effect on your application

NetworkChange.NetworkAvailabilityChanged -= myHandler

Please note this cleanup code can not be put in finalizer (becuase object is not yet garbage), you need to explicitly call it.

Another option is to go with some sort of weak delegate. .net frameworks still do not have any concept of Weak delegates, but there are some cool solutions developed for simulating weakreference semantics, which will be very useful in this situation. These solution mainly consider using a proxy object standing between your object and final object where you want to register events. Check the Greg's blog Simulating “Weak Delegates” in the CLR for nice explanation and pictorial representation..

There are also some other slight improvement versions of same solution

Simulating Weak Delegates for EventHandler-like Delegates (Ian Grifiths)

Weak Events (Xavier Musy)

 

This posting is provided "AS IS" with no warranties, and confers no rights