c# - 动态 System.Timers.Timer 和垃圾收集?

标签 c# .net

假设我动态创建一个这样的计时器:

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

当该引用超出范围时,Timer 对象是否会被垃圾回收?如果是这样,该事件还会火吗?如果不是,那么在这种情况下我该如何避免内存泄漏?

谢谢!

最佳答案

根据this answer ,计时器对象确实有资格进行垃圾收集,并在某个时刻停止触发事件。

但是,相反,垃圾收集会被阻止。如果我们有

publisher.SomeEvent += target.SomeHandler;

那么“publisher”将使“target”保持事件状态,但“target”不会使“publisher”保持事件状态。

关于c# - 动态 System.Timers.Timer 和垃圾收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760447/

相关文章:

c# - ApplicationData.LocalSettings 中的日期时间

c# - Azure 搜索 : Indexed document count does not match the total number of uploaded records

c# - 可以从字符串或内存流加载 App.Config 吗?

c# - SL3 透明/玻璃子窗口?

c# - 使用Vulcan Elasticsearch EPiServer映射错误

c# - 有什么理由为常量计算 INT 吗?

c# - 所有用户的列表 : Ldap referral error (LDAPReferralException)

c# - asp.net 表单运行服务器

c# - 如何对字符串中的位置执行 HitTest

c# - 为什么我们有这么多种程序集加载方法?