Search code examples
.netmemory-leaksc#-3.0threadpoolqueueuserworkitem

Memory leak when using .NET ThreadPool


I am using System.Threading.ThreadPool.QueueUserWorkItem() to run my tasks.

When running my application, I noticed it is taking a lot of memory and I took a dump file using the task manager. Investigting it, I found that many threads were stuck in the following stack:

ntdll!NtWaitForSingleObject+a 
KERNELBASE!WaitForSingleObjectEx+79 
mscorwks!CLREvent::WaitEx+174 
mscorwks!CLREvent::WaitEx+63 
mscorwks!ThreadpoolMgr::SafeWait+7b 
mscorwks!ThreadpoolMgr::WorkerThreadStart+11a 
mscorwks!Thread::intermediateThreadProc+78 
kernel32!BaseThreadInitThunk+d 
ntdll!RtlUserThreadStart+1d 

or

ntdll!NtWaitForWorkViaWorkerFactory+a 
ntdll!TppWorkerThread+2c9 
kernel32!BaseThreadInitThunk+d 
ntdll!RtlUserThreadStart+1d 

Why are these threads stuck? Am I using the wrong API? Maybe I am not managing the threads correctly?


Solution

  • The issue seems to be high CPU. According to:

    http://blogs.msdn.com/b/tess/archive/2008/02/27/net-debugging-demos-lab-4-high-cpu-hang-review.aspx

    When CPU is over 80%, new threads will pend.