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

Time:12-29

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?

CodePudding user response:

By default the Parallel.Invoke uses 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.

CodePudding user response:

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.

CodePudding user response:

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);
  • Related