Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newly created threads using Task.Factory.StartNew starts very slowly

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

like image 821
Morten Frederiksen Avatar asked Feb 26 '14 09:02

Morten Frederiksen


People also ask

What is the difference between task run and task factory StartNew?

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!

What is thread pool starvation?

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.

What is StartNew?

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)


1 Answers

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);
like image 188
Morten Frederiksen Avatar answered Oct 23 '22 08:10

Morten Frederiksen