I know how to write a Parallel.For
and a Parallel.ForEach
loop. Here is the sample code for both of them:
Parallel.For(0,10, (int i) = >
{
Console.Writeline(i);
});
Parallel.ForEach(fruits, fruit =>
{
Console.WriteLine("Fruit Name: {0}, Thread Id= {1}", fruit, Thread.CurrentThread.ManagedThreadId);
});
But the problem with both these code samples is the loops do not execute in sequence. How do I make them to execute in sequence? I have heard from people that you have to lock an object, then its possible. I have tried searching and tried lots of code samples but no use.
Furthermore, I would like to know whether the performance of parallel loops executed in sequence would be lesser or not? If no, why no? Because locking, would cause delay in my humble opinion.
As for my understanding of parallel programming, the scheduler makes the schedule at run-time. Can anyone tell what algorithm/strategy does .NET IDE use to schedule the code on several cores? Its goods to inside out of Parallel Programming.