user19177594
user19177594

Reputation:

Does Parallel.Invoke() create a new thread or use a thread from a thread pool?

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

Answers (3)

ShubhamWagh
ShubhamWagh

Reputation: 645

Here's how it works in steps.

  1. You call Parallel.Invoke().
  2. After that a new task or tasks gets created for the work that you want to execute.
  3. Those tasks get scheduled by TPL for execution.
  4. TPL schedules these tasks for execution by assigning threads from the thread pool.
  5. returns when all the tasks have finished executing.

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

Theodor Zoulias
Theodor Zoulias

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

Online demo.

Upvotes: 3

Vivek Nuna
Vivek Nuna

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

Related Questions