How to determine the counter inside Parallel.Foreach and stop this loop in a specific number

How to determine the counter inside Parallel.Foreach and Stop this mining in a specific number ?
I asked this question because this counter inside Parallel.ForEach does not work in normal action.
see this little example:

static void Main(string[] args) { int Count_Step = -1; string[] lines = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" }; List<string> list_lines = new List<string>(lines); ParallelOptions parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = 3; Parallel.ForEach(list_lines, parallelOptions, (line, state, index) => { if (Count_Step == 10) state.Stop(); Count_Step++; Console.WriteLine(index + " : " + line + " : " + Count_Step); //Thread.Sleep(5000); }); Console.ReadLine(); } 

I want 10 lines of output, not more!
How can i do this?

early

+4
source share
2 answers

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); ////Thread.Sleep(5000); }); Console.ReadLine(); } 

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]); ////Thread.Sleep(5000); }); Console.ReadLine(); } 

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]); ////Thread.Sleep(5000); } Console.ReadLine(); } 

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); ////Thread.Sleep(5000); } Console.ReadLine(); 

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 .

+11
source

Try Parallel.For()

Parallel.For Method

+4
source

Source: https://habr.com/ru/post/1436158/


All Articles