your calculate routine is too fast. it is quicker than the overhead of managing the parallel processing, so sequential is typically faster. you need to make the calculate take longer. also do not use the debugger, as it will affect the parallel process performance.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
const int LOOP_COUNT = 10000;
Console.WriteLine($"Call Calulate {LOOP_COUNT} times" );
SequentialCalcute();
ParallelCalcute();
long Calcute()
{
int Total = 0;
for (int i = 0; i < 10000; i++) // add more iteration to make parallel faster than sequential
{
Total = 20 / 4;
Total = 20 * 4;
Total = 20 ^ 4;
Total = 20 - 4;
Total = 20 % 4;
}
return Total;
}
void SequentialCalcute()
{
var Counter = 0;
Stopwatch SW = new Stopwatch();
SW.Start();
for (int i = 0; i < LOOP_COUNT; i++)
{
Calcute();
++Counter;
}
SW.Stop();
Console.WriteLine("Sequential Total seconds: " + SW.Elapsed.TotalSeconds + ", Counter: " + Counter);
}
void ParallelCalcute()
{
var Counter = 0;
Stopwatch SW = new Stopwatch();
SW.Start();
Parallel.For(0, LOOP_COUNT, i =>
{
Calcute();
Interlocked.Add(ref Counter, 1);
});
SW.Stop();
Console.WriteLine("Parallel Total seconds: " + SW.Elapsed.TotalSeconds + ", Counter: " + Counter);
}
Update: