Memory leak happens when using thread inside another thread
Below sample code has memory leak. If I comment out the two lines inside 开发者_如何学CRefreshTimer_Elapsed, then the memory leak is gone. Does anybody know what's wrong? Thanks for help.
static void RefreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Thread innerThread = new Thread(delegate() { });
innerThread.Start();
}
static void Main(string[] args)
{
System.Timers.Timer RefreshTimer = new System.Timers.Timer();
RefreshTimer.Interval = 5000;
RefreshTimer.Elapsed += new System.Timers.ElapsedEventHandler(RefreshTimer_Elapsed);
RefreshTimer.Start();
for (; ; )
{ }
}
Are you sure theres a memory leak? Or do you notice that your memory just grows?
Until the garbage collector cleans up all the threads you create, memory will grow, but its not leaking, the garbage collector knows that this is dead memory.
The only way memory "leaks" in a managed enviroment like .NET or java is when you have objects being referenced that are never used or needed. Thats not the case here. You're just creating a bunch of threads and forget about them immediately. As soon as they're no longer referenced by RefreshTimer_Elapsed and the thread stops running then there are no more references and they are free to be cleaned.
You won't see the memory drop until the garbage collector is ready to do a cleanup. You can try and force this but its not generally recommended for performance reasons.
What you see might be just resources not yet reclaimed by the Garbage collector because there is no memory pressure.
Also you have a busy for loop in your Main routine, you probably want a Thread.Sleep
statement there for testing, unless this is somehow part of this test...
To force a garbage collection just for your testing only you could replace your for loop with:
while(true)
{
Thread.Sleep(5000);
GC.Collect();
GC.WaitForPendingFinalizers();
}
In general when examining 'memory leaks' or resource problems in managed code I would recommend using a profiler (i.e. Redgate ANTS) and take a closer look at the allocations over time.
I think it's because you keep creating new threads.
The Timer object needs to be disposed!
It appears you are creating new items as there is a recursive call of the code and there may be some kind of loop developing at runtime causing untidy filling of memory with multiple copies of objects as every called item does not fully complete.
RefreshTimer_Elapsed makes a new thread every interval. What kind of work is the anonymous method doing? Is it completing? Every thread you make will get 1MB of virtual memory allocated via Windows.
If you threads never finish, then every interval, you will consume another 1MB of memory.
精彩评论