I'm trying to understand threads in C#. Whenever I pass the method in Parallel.Invoke()
it create a new thread or use thread from a thread pool?
By default the Parallel.Invoke
uses the current thread, and threads from the ThreadPool
. That's because the default value of the ParallelOptions.TaskScheduler
property is TaskScheduler.Default
, and the TaskScheduler.Default
schedules work on the ThreadPool
.
TaskScheduler defaultScheduler = new ParallelOptions().TaskScheduler;
Console.WriteLine($"defaultScheduler: {defaultScheduler}");
Console.WriteLine("defaultScheduler == TaskScheduler.Default: " +
(defaultScheduler == TaskScheduler.Default));
Output:
defaultScheduler: System.Threading.Tasks.ThreadPoolTaskScheduler
defaultScheduler == TaskScheduler.Default: True
Parallel.Invoke(
() => Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread),
() => Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread),
() => Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread)
);
Output:
False
True
True
Parallel.Invoke
method uses a thread pool to execute the provided methods concurrently. A thread pool is a collection of pre-allocated threads that can be used to execute tasks concurrently. When you call Parallel.Invoke
, it creates tasks for each of the provided methods and adds them to the thread pool for execution. The thread pool will then assign the tasks to threads in the pool and execute them concurrently.
Creating new threads can be a time-consuming operation. Using a thread pool allows you to reuse existing threads rather than creating new ones, which can save resources and improve performance.
Using a thread pool allows you to easily control the number of concurrent threads, as the pool has a fixed size. This can help prevent overloading the system with too many threads, which can negatively impact performance.
Here's how it works in steps.
Parallel.Invoke()
.task
or task
s gets created for the work that you want to execute.task
s get scheduled by TPL for execution. So to answer your question Parallel.Invoke()
does not create a new thread or get it from the thread pool. It's handled by TPL
If I've missed anything let me know.
This is my understanding of the topic.
It depends on how many tasks do you want to execute. If the number is less than 10, it will run them all in the thread pool. But you can change this behavior using property MaxDegreeOfParallelism
in ParallelOptions
:
Parallel.Invoke(new ParallelOptions { MaxDegreeOfParallelism = necessaryNumber }, yourTasks);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.