Skip to main content
Added relevant tags, formatting improvements.
Source Link
Theodor Zoulias
  • 46.1k
  • 8
  • 112
  • 155

What are the differences between using Parallel.ForEachParallel.ForEach or Task.Run()Task.Run() to start a set of tasks asynchronously?

Version 1:

List<string> strings = new List<string> { "s1", "s2", "s3" }; Parallel.ForEach(strings, s => { DoSomething(s); }); 

Version 2:

List<string> strings = new List<string> { "s1", "s2", "s3" }; List<Task> Tasks = new List<Task>(); foreach (var s in strings) { Tasks.Add(Task.Run(() => DoSomething(s))); } await Task.WhenAll(Tasks); 

What are the differences between using Parallel.ForEach or Task.Run() to start a set of tasks asynchronously?

Version 1:

List<string> strings = new List<string> { "s1", "s2", "s3" }; Parallel.ForEach(strings, s => { DoSomething(s); }); 

Version 2:

List<string> strings = new List<string> { "s1", "s2", "s3" }; List<Task> Tasks = new List<Task>(); foreach (var s in strings) { Tasks.Add(Task.Run(() => DoSomething(s))); } await Task.WhenAll(Tasks); 

What are the differences between using Parallel.ForEach or Task.Run() to start a set of tasks asynchronously?

Version 1:

List<string> strings = new List<string> { "s1", "s2", "s3" }; Parallel.ForEach(strings, s => { DoSomething(s); }); 

Version 2:

List<string> strings = new List<string> { "s1", "s2", "s3" }; List<Task> Tasks = new List<Task>(); foreach (var s in strings) { Tasks.Add(Task.Run(() => DoSomething(s))); } await Task.WhenAll(Tasks); 
Source Link
Petter T
  • 3.7k
  • 2
  • 22
  • 31

Parallel.ForEach vs Task.Run and Task.WhenAll

What are the differences between using Parallel.ForEach or Task.Run() to start a set of tasks asynchronously?

Version 1:

List<string> strings = new List<string> { "s1", "s2", "s3" }; Parallel.ForEach(strings, s => { DoSomething(s); }); 

Version 2:

List<string> strings = new List<string> { "s1", "s2", "s3" }; List<Task> Tasks = new List<Task>(); foreach (var s in strings) { Tasks.Add(Task.Run(() => DoSomething(s))); } await Task.WhenAll(Tasks);