I have a C# Windows Service that starts up various objects (Class libraries). Each of these objects has its own “processing” logic that start up multiple long running processing threads by using the ThreadPool. I have one example, just like this:
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(WorkerThread_Processing));
This works great. My app works with no issues, and my threads work well.
Now, for regression testing, I am starting those same objects up, but from a C# Console app rather than a Windows Service. It calls the same exact code (because it is invoking the same objects), however the WorkerThread_Processing method delays for up to 20 seconds before starting.
I have gone in and switched from the ThreadPool to a Thread, and the issue goes away. What could be happening here? I know that I am not over the MaxThreads count (I am starting 20 threads max).
The
ThreadPoolis specifically not intended for long-running items (more specifically, you aren’t even necessarily starting up new threads when you use theThreadPool, as its purpose is to spread the tasks over a limited number of threads).If your task is long running, you should either break it up into logical sections that are put on the
ThreadPool(or use the newTaskframework), or spin up your ownThreadobject.As to why you’re experiencing the delay, the MSDN Documentation for the
ThreadPoolclass says the following:You only know that the
ThreadPoolhasn’t reached its maximum thread count, not how many threads (if any) it actually has sitting idle.