Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When my timer ticks.... .NET Memory Leak

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.

like image 207
Jeff Avatar asked May 17 '11 16:05

Jeff


1 Answers

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.

like image 60
Allan W Avatar answered Sep 30 '22 10:09

Allan W