Will this get Garbage Collected?
Is this a valid way to use a Lambda as an EventHandler? It seems to me that the handler has been correctly removed and that the garbage collector should clean this up. However, I haven't seen anyone else do it this way, so I thought I'd better double check.
Along the same lines, what's the best tool (preferably free) to use to test whether this i开发者_StackOverflows in fact being garbage collected?
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(10);
EventHandler callback = null;
callback = (s, e) =>
{
timer.Stop();
timer.Tick -= callback;
};
timer.Tick += callback;
timer.Start();
A DispatcherTimer is kept alive by the Dispatcher class, it keeps a List<DispatcherTimer>
internally that stores a reference to any timer that's enabled. As soon as you Stop() the timer, the object gets removed from that list, making it eligible for garbage collection if you don't store any additional reference to it. Which you don't in this case, the timer reference is a local variable.
You cannot get a finalizer on the auto-generated class that implements the lambda. Next best thing is to simply run this code a billion times. If you don't get runaway member consumption and OOM then it obviously doesn't leak. You'll want to make the Interval shorter so it doesn't take until Christmas, 15 msec is good. Use a Timer to call the method so you don't get too many active timers at the same time and allow the dispatcher to do its job.
Yes, the callback will be eligible for garbage collection after the callback has executed once. This is a reasonable way of subscribing to an event in order to execute the handler just once.
It's tough to prove that the delegate will be garbage collected - or indeed that the object used to hold the captured variables callback
and timer
will be garbage collected, admittedly... you'd really want to put a finalizer there (which affects garbage collection itself, of course), but you can't as it's generated code.
精彩评论