Reputation: 984
In this parallel execution:
Parallel.For(0, 100, i =>
{
Console.WriteLine(i);
});
I am trying to get the same values of the below usual loop, so the "i" is always gave in an ascendent order, 0, 1, 2, 3, ... , 100
for(int i=0; i <=100; i++)
{
Console.WriteLine(i);
}
Is this possible, how could I control this parallel for execution regarding the order of the index ?
Upvotes: 1
Views: 407
Reputation: 2797
Once threading is involved, the order of execution is no longer guaranteed. You can technically get the results you're asking for by synchronizing everything, like so:
int actualIndex = 0;
var lockObject = new object();
Parallel.For(0, 100, i =>
{
lock(lockObject) Console.WriteLine(actualIndex++);
});
But, doing so simply adds the overhead of parallelism, then ensures that only one thread is doing something at a time - in other words, it's much worse than simply doing a regular for
loop!
If you need things to happen serially, the best you can do is either serialize via synchronization like lock
, or... simply do it serially.
What are you trying to accomplish, exactly?
Upvotes: 1
Reputation: 4280
If you want only results in ascending order, then this may work for you:
var results = new Dictionary<int>();
object lock = new object();
Parallel.For(0, 100, i =>
{
// here code runs in parallel
lock(lock) {
// here code runs sequentially
results[i];
}
});
// results from 0..100
var r = results.OrderBy(x => x.Key).Select(x => x.Value).ToList();
lock
creates what is known as critical section - inside lock
block of code may be only one thread at time, other threads must wait.
Parallel programming is a huge and complicated topic, here is a best course for C# programmers I ever read http://www.albahari.com/threading/part5.aspx
Upvotes: 0
Reputation: 171178
If you want that the execution of i
starts after i - 1
is done then there is no parallelism left and using a parallel loop is pointless.
A clever answer would be to build a string that has the 101 numbers separated by newlines and then print it. But that does not help you with your real use case I assume.
Upvotes: 1