I use ThreadPool.QueueUserWorkItem for creating a thread on Windows CE (I use .NET Framework 3.5). Sometimes the thread waits for something and starts too late. In the QueueUserWorkItem documentation it says that the delegate will be executed "when a thread pool thread becomes available".
Is there a way to force the ThreadPool to execute my delegate immediately? Would Thread.Start() be a solution for this?
Thank you!
First off, QueueUserWorkItem
doesn't create a thread, it merely places a "task" in the ThreadPool's queue for the workers to pick up and execute. In case of saturation (more tasks than available threads), there is no guarantee of when a worker will become available to execute the task. If you want immediate execution use an instance of Thread
instead. The only way to improve your odds with the ThreadPool is to increase the number of workers.
Edit: Just to be clear, if thread pool threads are indeed free, they will pick up work and execute it usually faster than starting a fresh thread.
A ThreadPool have a limited size. So you can't lunch as many thread as you want in the same time. If all the threads are busy then you have to wait for one to become available.
Check the number of thread you want to lunch and compare it to the Threadpool size -> GetMaxThreads()
Then if you want more thread just resize the pool with SetMaxThreads(int)
If you start a lot of threads from a pool you can get situation when there is no a free thread and your request is queued, that's why sometimes it starts to late. Try to increase a max number of worker threads in the pool. Use ThreadPool.SetMaxThreads
and ThreadPool.SetMinThreads
to configure the pool.