简体   繁体   中英

Memory leak happens when using thread inside another thread

Below sample code has memory leak. If I comment out the two lines inside RefreshTimer_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 (ie Redgate ANTS ) and take a closer look at the allocations over time.

我认为这是因为您不断创建新线程。

需要丢弃Timer对象!

似乎您正在创建新项目,因为有代码的递归调用,并且在运行时可能会出现某种循环,导致由于每个被调用项目未完全完成而导致对象的多个副本不完整地填充了内存。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM