Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有批处理逻辑的循环的C#for和并行for_C#_Asp.net_C# 4.0_Parallel Processing_Batch Processing - Fatal编程技术网

具有批处理逻辑的循环的C#for和并行for

具有批处理逻辑的循环的C#for和并行for,c#,asp.net,c#-4.0,parallel-processing,batch-processing,C#,Asp.net,C# 4.0,Parallel Processing,Batch Processing,我编写了一个for循环,用于处理将项目以20个为一批添加到列表中,如下所示: for (int i = 0; i < filteredList.Count; i = i + 20) { newlist.Add(GetResponse(filteredList.Skip(i).Take(20))); } Parallel.For(0,filteredList.Count, i=>{ i+=20; newlist.Add(GetResponse(filteredLi

我编写了一个for循环,用于处理将项目以20个为一批添加到列表中,如下所示:

  for (int i = 0; i < filteredList.Count; i = i + 20)
  {
    newlist.Add(GetResponse(filteredList.Skip(i).Take(20)));
  }
Parallel.For(0,filteredList.Count, i=>{
i+=20;
newlist.Add(GetResponse(filteredList.Skip(i).Take(20)));
});
但这并没有给我想要的结果。。。除了常规for循环外,还有什么方法可以更快地执行批插入,这样执行时间会比普通for循环快?

列表
不是线程安全的,这就是为什么

  Parallel.For(... {
    ...
    newlist.Add(GetResponse(filteredList.Skip(i).Take(20)));
    ...
  });
这是一种错误的技术。尝试改用并行Linq(Plinq):


你不能这么做。。。首先,我认为newList不是线程安全的?它是什么类型的收藏?此外,您还必须在将查询发送到线程之前具体化查询。。。因此,请执行.Skip().Take().ToList(),然后通过loop@Milney正确的newList不是线程安全的,我完全忘记了。。。如果我使用并发包而不是列表怎么办?@User987为什么要使用任何东西。您可以将其重写为PLINQ并将结果收集到列表中。您可以在PLINQ查询中添加生成
filteredList
的过滤操作,并加快整个查询的速度operation@PanagiotisKanavos你能给我举个例子吗?:)如果要将结果传递到
AddRange
,则不需要
ToList()
。另一方面,如果
newList
包含并行操作的结果,则只需将
ToList()
的结果分配给it@Panagiotis卡纳沃斯:谢谢!你说得很对:过早的物化-
.ToList()
-是evil@User987:很抱歉输入错误:
(value,index)=>new{value=value,index=index}
@User987:需要更多咖啡:;(
item.index/20
-
index
应位于较低的位置case@User987:我个人不得不为N+1次编辑道歉
newList.AddRange(filteredList
  .AsParallel()
  .Select((value, index) => new {
     value = value,
     index = index })
  .GroupBy(item => item.index / 20)
  .Select(chunk => GetResponse(chunk.Select(item => item.value))));