zSy*_*sis 4 .net c# parallel-processing .net-4.0
我运行了以下代码,随着时间的推移(一两个小时),我注意到迭代项目需要更长时间.我正在做的事情导致这种情况发生吗?如果是这样我该怎么办呢?
int totalProcessed = 0;
int totalRecords = MyList.Count();
Parallel.ForEach(Partitioner.Create(0, totalRecords), (range, loopState) =>
{
for (int index = range.Item1; index < range.Item2; index++)
{
DoStuff(MyList.ElementAt(index));
Interlocked.Increment(ref totalImported);
if (totalImported % 1000 == 0)
Log(String.Format("Processed {0} of {1} records",totalProcessed, totalRecords));
}
});
public void DoStuff(IEntity entity)
{
foreach (var client in Clients)
{
// Add entity to a db using EF
client.Add(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
Vic*_*din 10
ElementAt 扩展方法非常慢,具有以下实现:
public static void T ElementAt(this IEnumerable<T> collection, int index)
{
int i = 0;
foreach(T e in collection)
{
if(i == index)
{
return e;
}
i++;
}
throw new IndexOutOfRangeException();
}
Run Code Online (Sandbox Code Playgroud)
很明显,当索引更大时,它的工作时间更长.您应该使用索引器MyList[index]而不是ElementAt.
| 归档时间: |
|
| 查看次数: |
2388 次 |
| 最近记录: |