Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Parallel.Invoke same as calling multiple Task.Run's?

Task.Run: Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.

Parallel.Invoke: Executes each of the provided actions, possibly in parallel.

Effectively they spin up a new thread from the thread pool. So is Parallel.Invoke same as calling multiple Task.Runs?

like image 553
variable Avatar asked Dec 17 '25 05:12

variable


1 Answers

So you want to compare these two techniques:

Parallel.Invoke(source.Select(source => () => ProcessItem(source)).ToArray());
Task.WaitAll(source.Select(source => Task.Run(() => ProcessItem(source))).ToArray());

There is one similarity and two differences. The similarity is that in both cases all actions will be invoked and completed before the Parallel.Invoke/Task.WaitAll returns. It doesn't matter if some of the actions fail. There is no support for a fail-fast strategy.

The two differences are:

  1. The Parallel.Invoke uses the current thread as one of the worker threads. On the contrary the Task.WaitAll+Task.Run uses exclusively ThreadPool threads. While the worker threads are working, the current thread is blocked doing nothing.

  2. The Parallel.Invoke can be configured with a specific MaxDegreeOfParallelism, TaskScheduler and CancellationToken (ParallelOptions). This is not possible with the Task.Run. It is possible with the Task.Factory.StartNew, but comparatively it's quite cumbersome.

like image 58
Theodor Zoulias Avatar answered Dec 19 '25 22:12

Theodor Zoulias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!