This Question based on this question:
How to dispose the local variable that contains event
Someone said:one event handler to an instance,the reference count of the instance will added? why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your linked question, as Jon Skeet states, has it backwards. The only thing keeping
watcheralive is perhaps its own internal implementation where it may (or may not) register an event with a lower-level object that is responsible for feeding back “ticks”. -but this is just conjecture.Clicking the button twice will yield two separate
watcherinstances, each with one subscriber to thePositionChangedevent (which just happens to be the same method on the same instance).Importantly, it isn’t the
PositionChangedsubscriber that is keepingwatcheralive after the method quits – it is something else (I suspect buried within theGeoCoordinateWatcherimplementation). When the method exits, a reference to a particular instance ofwatcheris correctly popped off the stack, but due to another reference being held onwatcherthe effective reference count in the eyes of the CLR is still greater than zero – therefore, not eligible for garbage collection.Because of this, it will continue on to fire the
PositionChangedevent. As nothing in the event stops the watcher from continuing, I’m going to guess you may have a memory leak because each button click will create and leave alive a watcher instance.You either need to store and use only one
GeoCoordinateWatcherclass, or close-off / dispose / stop it each time you handle the event.The usual consideration with events and subscriptions is being mindful of short-lived objects subscribing to long-lived objects.
Delegates hold references to a particular method in a particular instance of a class (or just the type itself if it were a static method). Subscribing to an event causes the event publisher to inadvertently hold a reference to the subscriber instance via the subscription’s delegate.
Obviously, if you register a static method as an event handler, you won’t get this reference count because there is no instance.
A memory leak can occur if the subscriber is short-lived and the event publisher is long-lived, if you don’t unsubscribe. Assume the subscriber would like to be eligible for GC, because it has an active subscription against an event somewhere and that object still lives, it cannot be eligible until it is removed from that subscription list.