.Net Memory Leak when creating lots of threads

2019-02-03 15:30发布

I have an application that creates lot of threads over time. I noticed that memory usage grows as it runs and eventually runs out of memory. But the same code doesn't leak memory on my coworker's environment. We both have same .net version. I was able to reproduce the issue with the following sample code which doesn't leak on my coworker's laptop but does on my laptop.

public static void Main(string[] args)
{           
    Console.WriteLine("Version " + Environment.Version.ToString());

    if (Environment.Is64BitProcess) 
        Console.WriteLine("64"); 
    else 
        Console.WriteLine("32");

    while(true)
    {
        Thread t = new Thread(() => { Thread.Sleep(1); });
        t.IsBackground = true;
        t.Start();
        Thread.Sleep(1);               
    }
}

When I run the above, it prints the following

Version 4.0.30319.18063
32

In Visual Studio 2012 the target framework for the project is .net framework 4.5. The project leaks memory with following configuration

Project Properties -> Build
    Platform target: Any CPU
    Prefer 32-bit: checked

If I unchecked Prefer 32-bit, it doesn't leak.

Another configuration that leaks memory is

Project Properties -> Build
    Platform target: x86
    Prefer 32-bit: disabled

The resulting executable that leaks on my laptop doesn't leak on my coworker's laptop.

I used CLR Profiler to find memory leaks but it doesn't show anything that's leaking. But I do see that working set in windows resource monitor increases by about 1 MB/sec.

What is causing the memory usage to increase in 32-bit mode on my environment but not my coworker's?

2条回答
贼婆χ
2楼-- · 2019-02-03 15:50

You should limit the number of simultaneous threads you are running at the same time and maybe you can using the thread pool, so you can queue threads that are added and exceeding the pool size you define.

https://msdn.microsoft.com/en-us/library/h4732ks0.aspx

查看更多
神经病院院长
3楼-- · 2019-02-03 15:53

I've read all comments and afraid that my comment will be lost there, so try to answer.

Use memory profiler designed for .NET applications, JetBrains dotMemory or ANTS or whatever but WinDBG or Task Manager or other native memory tools.

You can compare how app behaves on your and your colleague's laptops using realtime chart of chosen profiler. I guess you will see that memory usage constantly increases on your laptop - just get a memory snapshot and see how many Thread objects are in memory, what objects take most of the memory and investigate why and by whom are they held in memory.

查看更多
登录 后发表回答