When my timer ticks… .NET Memory Leak

混江龙づ霸主 提交于 2019-12-22 04:56:14

问题


I have a .NET System.Threading.Timer timer that ticks every 60 seconds and introduces a memory leak on each tick.

On each tick of the timer, the code allocates an IDisposable object (called SocketsMessageConnector)...but I do dispose it correctly.

I ran .NET Memory Profiler and every 60 seconds I see a new instance of my SocketsMessageConnector class lingering in memory (so after 15 minutes, I have 15 instances). The memory profiler verifies that the instance is in fact disposed, but it shows the instance rooted by a TimerCallback, which is rooted by a _TimerCallback, which is rooted by a GCHandle...

What's up here? Why is the TimerCallback holding on to the new instance created on every timer tick?

PS. The profiler forces 2 GCs before taking a snapshot, so I know it IS in fact a leak and not just an optimization by the GC.


回答1:


Just because it's been disposed, doesn't mean that it's been Garbage Collected yet.

Try changing your timer to run twice a second, and then let it run for 10 minutes. Now check how many of your class objects are still "lingering in memory". If you truely have a memory leak, you'll have 1200 objects. But if Garbage Collection has jumped in, you'll have considerably less - perhaps under 100.



来源:https://stackoverflow.com/questions/6034355/when-my-timer-ticks-net-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!