System.Timers.Timer的动态和垃圾收集? [英] Dynamic System.Timers.Timer and Garbage Collection?

查看:197
本文介绍了System.Timers.Timer的动态和垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我动态创建一个这样的计时器:

Let's say I dynamically create a timer like this:

        System.Timers.Timer expirationTimer = new Timer(expiration * 60000);
        expirationTimer.Elapsed += (sender, e) => removeExpiredCacheEntry(sessionID);
        expirationTimer.Start();

在该引用超出范围时,将计时器对象被垃圾收集?如果是这样,将在活动仍然火?如果没有,那么我将如何避免这种情况的内存泄漏?

When that reference goes out of scope, will the Timer object be garbage collected? If so, will the event still fire? If not, then how would I avoid a memory leak in this situation?

谢谢!

推荐答案

根据这个答案,定时器将对象的确有资格进行垃圾回收,并停止在某一时刻触发事件。

According to this answer, the timer object will indeed be eligible for garbage collection and cease to fire events at some point.

然而,垃圾收集是$ P $围绕pvented的其他方式。如果我们有

However, garbage collection is prevented the other way around. If we have

publisher.SomeEvent += target.SomeHandler;

然后发布者,将让目标活着,但目标不会保持发行人活着。

then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.

这篇关于System.Timers.Timer的动态和垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆