https://github.com/arnab-developer/maxdegreeofparallelism
Max degree of parallelism with Parallel.ForEach() method
https://github.com/arnab-developer/maxdegreeofparallelism
Last synced: 3 months ago
JSON representation
Max degree of parallelism with Parallel.ForEach() method
- Host: GitHub
- URL: https://github.com/arnab-developer/maxdegreeofparallelism
- Owner: Arnab-Developer
- License: mit
- Created: 2021-05-23T10:58:11.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2021-05-23T11:17:18.000Z (about 4 years ago)
- Last Synced: 2025-01-17T02:24:16.996Z (5 months ago)
- Language: C#
- Size: 10.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Max degree of parallelism
A demo to take input from user and use that as max degree of parallelism
with `Parallel.ForEach()` method.`Parallel.ForEach()` method can process items in a collection in multiple
threads parallelly but we can specify the max number of parallel threads
in that.One of the overload of `Parallel.ForEach()`
``` csharp
public static ParallelLoopResult ForEach(
IEnumerable source, ParallelOptions parallelOptions, Action body);
```Usage
``` csharp
Parallel.ForEach(
students,
new ParallelOptions() { MaxDegreeOfParallelism = 2 },
student =>
{
Console.WriteLine($"Id: {student.Id}, Name: {student.FirstName} {student.LastName}");
Thread.Sleep(2000);
});
```## Output
```
---- PrintSingleThread
Thread id: 1, Id: 1, Name: f1 l1
Thread id: 1, Id: 2, Name: f2 l2
Thread id: 1, Id: 3, Name: f3 l3
Thread id: 1, Id: 4, Name: f4 l4
Thread id: 1, Id: 5, Name: f5 l5
Thread id: 1, Id: 6, Name: f6 l6
Thread id: 1, Id: 7, Name: f7 l7
Thread id: 1, Id: 8, Name: f8 l8
Thread id: 1, Id: 9, Name: f9 l9
Thread id: 1, Id: 10, Name: f10 l10
Time took: 20 sec---- PrintMultiThread
Thread id: 1, Id: 1, Name: f1 l1
Thread id: 4, Id: 6, Name: f6 l6
Thread id: 5, Id: 2, Name: f2 l2
Thread id: 6, Id: 7, Name: f7 l7
Thread id: 1, Id: 3, Name: f3 l3
Thread id: 7, Id: 5, Name: f5 l5
Thread id: 4, Id: 8, Name: f8 l8
Thread id: 5, Id: 10, Name: f10 l10
Thread id: 1, Id: 4, Name: f4 l4
Thread id: 4, Id: 9, Name: f9 l9
Time took: 6 secProvide max degree of parallelism value: 2
---- PrintMultiThreadWithMaxDegreeOfParallelism
Thread id: 4, Id: 1, Name: f1 l1
Thread id: 1, Id: 6, Name: f6 l6
Thread id: 1, Id: 7, Name: f7 l7
Thread id: 5, Id: 2, Name: f2 l2
Thread id: 1, Id: 8, Name: f8 l8
Thread id: 5, Id: 3, Name: f3 l3
Thread id: 1, Id: 9, Name: f9 l9
Thread id: 5, Id: 4, Name: f4 l4
Thread id: 1, Id: 10, Name: f10 l10
Thread id: 5, Id: 5, Name: f5 l5
Time took: 10 sec
```