如何在 Parallel.Foreach 中定义计数器并以特定数量停止该战利品?
我问这个问题是因为 Parallel.ForEach 中的计数器在常规操作中不起作用。
请看这个小例子:
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();
}
我想要输出 10 行,而不是更多!
我怎样才能做到这一点?
提前致谢