如何在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行,而不是更多! 我怎么能这样做?
提前致谢
答案 0 :(得分:11)
如果您只想输出10行,请改为
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();
}
替代地
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();
}
甚至
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();
}
如果您真的希望并行迭代更新循环外的某些值,那么您需要确保更改变量的所有更新和读取都是线程安全的。
如果要递增整数,可以这样做。
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();
但是,thisCount
的输出在控制台窗口中并不是连续的,在两行之间可能会有一个线程切换。
如果你想做更复杂的事情,比如取消处理,你应该看一下BlockingCollection。
答案 1 :(得分:4)
尝试Parallel.For()