In an WPF/c# application that uses around 50-200 of short living worker-threads created by Task.Factory.StartNew
it takes from 1 to 10 seconds before the newly created thread starts executing.
What is the reason for this very slow thread execution start?
Update: The delay is excatly 500 msec
Task. Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!
ThreadPool starvation occurs when the pool has no available threads to process new work items and it often causes applications to respond slowly. Using the provided example ASP.NET Core web app, you can cause ThreadPool starvation intentionally and learn how to diagnose it.
StartNew(Action) Creates and starts a task for the specified action delegate. StartNew(Action<Object>, Object) Creates and starts a task for the specified action delegate and state. StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)
Found out that the thread pool can be unwilling to start more than one new thread every 500 msec when the number of thread pool threads used are over a specific value. However increasing MinThreads using ThreadPool.SetMinThreads - even though it is not recommended - to 100 enables me to create 100 threads without the 500 msec delay.
Here's what helped me:
http://alexpinsker.blogspot.com/2009/06/threadpool.html
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setminthreads%28v=vs.100%29.aspx
https://stackoverflow.com/a/13186389/600559
Edit:
Here's what I ended doing in App.xaml.cs
(in the constructor):
// Get thread pool information
int workerThreadsMin, completionPortThreadsMin;
ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin);
int workerThreadsMax, completionPortThreadsMax;
ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax);
// Adjust min threads
ThreadPool.SetMinThreads(workerThreadsMax, completionPortThreadsMin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With