Possible Duplicate:
Do event handlers stop garbage collection from occuring?
I had one wp7 application like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
watcher.Start();
}
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
Debug.WriteLine(e.Position.Timestamp.ToString());
}
After I click the button twice,the Console will output the Timestamp twice.
But the watcher was a local variable!
What’s wrong with it?
And how can I distory it?
watcheris a local variable, but that doesn’t affect the object necessarily. You’ve asked theGeoCoordinateWatcherto start – I’d expect it to maintain a reference to itself, effectively, or stash one somewhere appropriate.It sounds like either you ought to disable the button once it’s clicked, or you need to keep the watcher in an instance variable so that you can dispose of the old one and create a new one. (I’m not sure why that would be useful though.)
EDIT: As there are two incorrect answers here, let me just clear something up… an event publisher (the watcher in this case) has references to the handler delegates. If those delegates refer to instance methods (as it does in this case) then there’s a reference to an instance of the type containing that method:
That means that as long as the publisher isn’t garbage collected (and the event handler still exists), the instance associated with the delegate can’t be collected. It doesn’t prevent the publisher itself from being garbage collected.
In other words, if
GeoCoordinateWatcherdidn’t do something “special” (probably in theStartmethod) it could be garbage collected. There’s no implicit reference from an event handler to the event publisher which prevents it from being garbage collected that way round.