If you only want to print 10 lines,
static void Main(string[] args) { var lines = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ... }; var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = 3 }; Parallel.ForEach(lines.Take(10), parallelOptions, (line, index) => { Console.WriteLine("{0} : {1}", index, line);
as an alternative
static void Main(string[] args) { var lines = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ... }; var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = 3 }; Parallel.For(0, 9, parallelOptions, i => { Console.WriteLine("{0} : {1}", i, lines[i]);
or even
static void Main(string[] args) { var lines = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ... }; Enumerable.Range(0, 10).AsParallel().WithDegreeOfParallelism(3).ForAll(i => { Console.WriteLine("{0} : {1}", i, lines[i]);
If you really want your parallel iterations to update some value outside the loop, you need to make sure that all updates and readings of the variable being changed are thread safe.
If you increment an integer, you can do it as follows.
var stepCount = 0; Enumerable.Range(0, 10).AsParallel().WithDegreeOfParallelism(3).ForAll(i => { var thisCount = Interlocked.Increment(ref stepCount); Console.WriteLine("{0} : {1} : {2}", i, lines[i], thisCount);
However, the output of thisCount not necessary in order to be adjacent in the console window; there may be a stream switch between the two lines.
If you want to do something more complex, for example, to cancel part processing, you should take a look at BlockingCollection .