c# - 使用列表和并行循环时出现异常

标签 c# arrays list c#-4.0 parallel-processing

我编写了如下代码:

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

我试图用上面的代码实现的是比较两个列表

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

如果它们不存在于“itm”列表中,则会将其添加到

missingList.Add(f);

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

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

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

它说:

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

我在这里做错了什么?

附注伙计们,ListToUpdate 和 Missing 列表都是简单的列表,这就是导致这里问题的原因吗?

最佳答案

不要使用List<T>具有多个线程。它们不是线程安全的。

考虑使用 System.Collections.Concurrent 中的集合.

关于c# - 使用列表和并行循环时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007593/

相关文章:

c# - 从 iOS 使用 AD 进行身份验证

c# - 将空查询字符串参数视为空字符串,而不使用参数类

c# - 如何将具有十六进制代码序列的文本文件转换为字节数组?

C# 使用 Lists 读取、写入和搜索文本文件行

c# - 如何通过 Redis 服务器转换具有多种数据类型的 MemoryStream

c# - VB.NET 'Char' 值无法转换为 'Integer'

java - 将数组拆分为两个总和最小的子数组

c - 这在 C 中意味着什么

python - 将一个列表中随机选择的元素插入另一个列表

python - 根据列表项的索引模进行不同的操作