这会被垃圾收集吗?
这是使用 Lambda 作为事件处理程序的有效方法吗?在我看来,处理程序已被正确删除,垃圾收集器应该清理它。但是,我还没有看到其他人这样做,所以我想我最好仔细检查一下。
同样,用于测试这是否确实被垃圾收集的最佳工具(最好是免费的)是什么?
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();
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 is 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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DispatcherTimer 由 Dispatcher 类保持活动状态,它在内部保留一个
List
,用于存储对任何已启用的计时器的引用。一旦您 Stop() 计时器,该对象就会从该列表中删除,如果您不存储对该对象的任何其他引用,则该对象有资格进行垃圾回收。在本例中您不需要,计时器引用是一个局部变量。您无法在实现 lambda 的自动生成的类上获得终结器。接下来最好的事情就是简单地运行此代码十亿次。如果你没有出现会员消费失控和 OOM 的情况,那么它显然不会泄漏。您需要缩短间隔时间,这样就不需要等到圣诞节,15 毫秒就可以了。使用计时器来调用该方法,这样您就不会同时获得太多活动计时器并允许调度程序完成其工作。
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.
是的,回调执行一次后就可以进行垃圾回收。这是订阅事件以便仅执行处理程序一次的合理方式。
很难证明委托将被垃圾收集 - 或者实际上用于保存捕获的变量
callback
和timer
的对象将是垃圾诚然,你确实想在那里放置一个终结器(当然,这会影响垃圾收集本身),但你不能,因为它是生成的代码。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
andtimer
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.