How Can I Define Counter Inside Parallel.Foreach And Stop That Loot In A Specific Number?
I asked this Question because that counter inside Parallel.ForEach does not work in a regular action.
please 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 in output, not more!
how can i do that?
thanks in advance
If you only want to output 10 lines do this instead,
alternatively
or even
If you really want your parallel iterations to update some value outside the loop, then you will need to ensure all updates and reads of the changing variable are thread-safe.
If you are incrementing an integer you could do it like this.
However, the output of
thisCountis not garaunteed to be contiguous in the console window, there could be a thread switch between the two lines.If you want to do somthing more sophisticated, like cancelling the processing part way through you should take a look at BlockingCollection.