Reputation:
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?
Upvotes: 2
Views: 768
Reputation: 645
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.
Upvotes: 0
Reputation: 43846
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
Upvotes: 3
Reputation: 1
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.
Upvotes: 0