Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

multithreading - Using TPL how do I set a max threadpool size

I am using the TPL to add new tasks to the system thread pool using the function Task.Factory.StartNew(). The only problem is that I am adding a lot of threads and I think it is creating too many for my processor to handle. Is there a way to set a maximum number of threads in this thread pool?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The default TaskScheduler (obtained from TaskScheduler.Default) is of type (internal class) ThreadPoolTaskScheduler. This implementation uses the ThreadPool class to queue tasks (if the Task isn't created with TaskCreationOptions.LongRunning - in this case a new thread is created for each task).

So, if you want to limit the # of threads available to Task objects created via new Task(() => Console.WriteLine("In task")), you can limit the available threads in the global threadpool like this:

// Limit threadpool size
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
workerThreads = 32;
ThreadPool.SetMaxThreads(workerThreads, completionPortThreads);

The call to ThreadPool.GetMaxThreads() is done to avoid shrinking the completionPortThreads.

Note that this may be a bad idea - since all Tasks without a specified scheduler, and any number of other classes use the default ThreadPool, setting the size too low could cause side-effects: Starvation, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...