Comments on: How to Execute Multiple Tasks Asynchronously in C# https://code-maze.com/csharp-execute-multiple-tasks-asynchronously/ Learn. Code. Succeed. Mon, 05 Dec 2022 15:31:38 +0000 hourly 1 https://wordpress.org/?v=6.7.5 By: Angelru https://code-maze.com/csharp-execute-multiple-tasks-asynchronously/#comment-6999 Mon, 05 Dec 2022 15:31:38 +0000 https://drafts.code-maze.com/?p=72178#comment-6999 In reply to Chayan.

I am using it in a .NET MAUI application, where I always get a list of 20 elements, I am making a call to the google API. Thanks for the explanation. I don’t know what the correct value would be…

]]>
By: Chayan https://code-maze.com/csharp-execute-multiple-tasks-asynchronously/#comment-6998 Mon, 05 Dec 2022 13:58:54 +0000 https://drafts.code-maze.com/?p=72178#comment-6998 In reply to Angelru.

The default MaxDegreeOfParallelism for the Parallel.ForEachAsync is equal to the Environment.ProcessorCount, and for all other Parallel methods(For and ForEach) it is equal to -1, which means unlimited parallelism.

The optimal value for the MaxDegreeOfParallelism for CPU-bound operations is Environment.ProcessorCount, although oversubscription might help if the workload is unbalanced.

The Parallel.ForEachAsync is used typically for I/O-bound asynchronous operations, where the sweet spot depends on the capabilities of the remote server or the bandwidth of the network. So in this case there is no rule of thumb, you will have to start with a number and fine-tune it depending on performance.

In this example, we have set the value to 3 simply as we wanted to make at max 3 parallel calls. So you can set it to 20 if your remote service and network can support such concurrent requests. But please also remember, when the CPU has to switch from one thread to another (context switch) it has a cost, so if you use too many threads and the CPU is switching all the time, you decrease the performance.

]]>
By: Angelru https://code-maze.com/csharp-execute-multiple-tasks-asynchronously/#comment-6997 Mon, 05 Dec 2022 07:27:33 +0000 https://drafts.code-maze.com/?p=72178#comment-6997 Hello, so far I use Task.WhenAll to execute multiple tasks like in the example you have given, but I want to use Parallel.ForeachAsync.

I have seen MaxDegreeOfParallelism you have set it to 3. is that because _employeeIds contains 3? If I had 20, would I have to put 20?

]]>
By: Dennis https://code-maze.com/csharp-execute-multiple-tasks-asynchronously/#comment-6354 Wed, 17 Aug 2022 17:43:14 +0000 https://drafts.code-maze.com/?p=72178#comment-6354 Thank you for the extensive post and benchmarking. While I would write some of the code differently, I appreciate your work and different opinions!
Justing starting out as a blogger, I recently posted an in-depth article on best practices in async-await in C#. Maybe you might want to have a go.
Cheers,

]]>