.Net Memory Leak when creating a large number of threads

I have an application that creates a lot of threads over time. I noticed that memory usage increases as it starts up and eventually ends up in memory. But the same code is not a memory leak in my colleague environment. We have both versions of .net. I was able to reproduce the problem with the following code example that does not leak on my laptop but 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 above, it prints the following

 Version 4.0.30319.18063 32 

In Visual Studio 2012, the target structure for the project is .net framework 4.5. Memory leak project followed by configuration

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

If I uncheck Prefer 32-bit, it does not flow.

Another configuration that has memory leaks,

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

The resulting executable that runs on my laptop does not flow on my laptop.

I used the CLR Profiler to search for memory leaks, but it does not show anything that leak. But I see that the working set in the Windows Resource Monitor is increasing by about 1 MB / s.

What causes an increase in memory usage in 32-bit mode in my environment, but not in my colleague?

+7
memory-management multithreading c # memory-leaks
source share
2 answers

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

Use a memory profiler designed for .NET, JetBrains dotMemory or ANTS applications, or any other than WinDBG or task manager or other built-in memory tools.

You can compare how the application behaves on your laptops and colleagues using the chart of the selected chart in real time. I think you will see that the memory usage is constantly increasing on your laptop - just get a snapshot of the memory and see how many Thread objects are in memory, which objects occupy most of the memory and explore why and by whom they are stored in memory.

0
source share

You should limit the number of simultaneous threads that you execute at the same time, and perhaps you can use the thread pool so that you can queue threads that are added and exceed the size of the pool that you define.

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

-2
source share