c# - How to dispose the local variable that contains event -
possible duplicate:
do event handlers stop garbage collection occuring?
i had 1 wp7 application 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 click button twice,the console output timestamp twice. watcher local variable! what's wrong it? , how can distory it?
watcher
local variable, doesn't affect object necessarily. you've asked geocoordinatewatcher
start - i'd expect maintain reference itself, effectively, or stash 1 somewhere appropriate.
it sounds either ought disable button once it's clicked, or need keep watcher in instance variable can dispose of old 1 , create new one. (i'm not sure why useful though.)
edit: there 2 incorrect answers here, let me clear up... event publisher (the watcher in case) has references handler delegates. if delegates refer instance methods (as in case) there's reference instance of type containing method:
event publisher => delegate => instance of type handler method
that means long publisher isn't garbage collected (and event handler still exists), instance associated delegate can't collected. doesn't prevent publisher being garbage collected.
in other words, if geocoordinatewatcher
didn't "special" (probably in start
method) could garbage collected. there's no implicit reference event handler to event publisher prevents being garbage collected way round.
Comments
Post a Comment