Difference between Parallel foreach vs Foreach Task
Program
class Program
{
static void Main(string[] args)
{
Test testObj = new Test();
string[] testStringArray = new string[10];
Console.WriteLine("\tTasks");
Program.CallAsyncMethod(testStringArray);
Console.WriteLine("\n\tParallel");
Parallel.ForEach<string>(testStringArray, p => testObj.display_string("Some output"));
}
public static async void CallAsyncMethod(string[] test)
{
Test testObj = new Test();
for (int i = 0; i < test.Length; i++)
{
Boolean result =await testObj.display_String_Async(i.ToString());
}
}
}
public class Test
{
static int count = 0;
public void display_string(string numStr)
{
Console.WriteLine("Number : " + numStr);
Console.WriteLine("Count : " + count++);
}
public async Task<Boolean> display_String_Async(string numbStr)
{
Console.WriteLine("Number : " + numbStr);
Console.WriteLine("Count : " + count++);
return true;
}
}
Output
Tasks
Number : 0
Count : 0
Number : 1
Count : 1
Number : 2
Count : 2
Number : 3
Count : 3
Number : 4
Count : 4
Number : 5
Count : 5
Number : 6
Count : 6
Number : 7
Count : 7
Number : 8
Count : 8
Number : 9
Count : 9
Parallel
Number : Some output
Count : 10
Number : Some output
Count : 11
Number : Some output
Number : Some output
Number : Some output
Number : Some output
Count : 15
Number : Some output
Count : 14
Number : Some output
Count : 17
Count : 12
Count : 13
Number : Some output
Count : 18
Number : Some output
Count : 19
Count : 16
So basically when a task is created it creates a thread for each but when we do the same using parallel than system can create multiple threads to complete each requests.
When you have a piece of work completely independent from each other than only you should use parallel,
It's very fast but gives overhead to the CPU cycles .
Thank for reading this.