使用列表循环和并行循环时获取异常 [英] Getting exception when working with list and parallel loops

查看:51
本文介绍了使用列表循环和并行循环时获取异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的代码:

Parallel.ForEach(filteredList, (f) =>
{
    var conditionMatchCount = itm.AsParallel().Max(i =>
        // One point if ID matches
        ((i.ItemID == f.ItemID) ? 1 : 0) +
        // One point if ID and QuantitySold match
        ((i.ItemID == f.ItemID && i.QuantitySold == f.QuantitySold) ? 1 : 0)
    );
    // Item is missing
    if (conditionMatchCount == 0)
    {
        ListToUpdate.Add(f);
        missingList.Add(f);
    }
    // Item quantity is different
    else if (conditionMatchCount == 1)
    {
        ListToUpdate.Add(f);
    }
});

我基本上有两个列表:

// itm - list whos data comes from DB 
// filteredList => whos data comes from an external source

我想通过上面的代码实现的是比较两个列表

What I'm trying to achieve with the code above is to compare the two lists

并查看"itm"列表中不存在filteredList(新项目)中的哪些项目...

and see which items from filteredList (new one) are not present in "itm" list...

如果它们不在itm"列表中,它们将被添加到

If they are not present in "itm" list, they are added to

missingList.Add(f);

所有具有与"itm"列表中的那个不同的QuantitySold属性的任何项目,我也将它们添加到ListToUpdate;

Also any items that have different QuantitySold property different than the one in "itm" list, I add them as well to ListToUpdate;

我在这里遇到的错误在以下行中:

The error that I'm getting here is on the following line:

else if (conditionMatchCount == 1)
{
    ListToUpdate.Add(f);
}

它说:

目标数组不够长.检查destIndex和length以及数组的下界

Destination array was not long enough. Check destIndex and length and the array's lower bounds

我在做什么错了?

P.S.伙计们,ListToUpdate 和 Missing 列表都是简单的列表,这是导致问题的原因吗?

P.S. Guys, both ListToUpdate and Missing list are plain simple lists, is that whats causing the issue here?

推荐答案

不要在多个线程中使用 List< T> .它们不是线程安全的.

Don't use List<T> with multiple threads. They aren't thread safe.

考虑使用 System.Collections.Concurrent .

这篇关于使用列表循环和并行循环时获取异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆