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
Comments
- Anonymous
December 14, 2005
Great article Adarsh.. Saw your other article on object pooling too.. Awesome Keep posting such nice articles. - Anonymous
February 10, 2006
Ian Griffiths' solution didn't do it for me, so I rolled my own. I've put up a weak event handler example on code project if you are interested at http://www.codeproject.com/csharp/weakeventhandlerfactory.asp - Anonymous
September 07, 2006
Good Article.
I have one question. When the application is starting how do i check if the application has Ineternet connection
My email is vik20000in@gmail.com
Thanks in advance
Vikram - Anonymous
May 30, 2008
PingBack from http://stevenhome.joolo.com/usingeventhandler.html