Parallel.foreach不会处理所有项目

Sae*_*ari 3 c# foreach multithreading visual-studio parallel.foreach

我在这里有问题.我试图使用Parallel.foreach将我的数据表转换为列表对象.像这样 .

public List<ProductList> GetProductList(DataTable table)
{
    List<ProductList> list = new List<ProductList>();
    Parallel.ForEach(table.AsEnumerable(), item =>
    {

            string sku = item["product_sku"].ToString();
            //int skus = Convert.ToInt16(item["product_sku"]);

            string price = item["product_price"].ToString();

            string tweakerID = item["ID"].ToString();
            string finalPrice = item["FinalPrice"].ToString();
            list.Add(new ProductList() { SKU = sku, Price = price, ID = id, FinalPrice = finalPrice });


    });





    list.RemoveAll(item => item == null);

    return list;
} 
Run Code Online (Sandbox Code Playgroud)

我有超过65000个产品行.在此之后.列表中只添加了约63000种产品.但结果不是修正号码.例如,我运行此代码的最后三次我有63202,64025,62920.每次都是一个新号码.

我也不例外.

mad*_*dev 8

多数民众赞成因为List<T>不安全.试试:ConcurrentBag<T>相反.

ConcurentBag存在于System.Collections.Concurrent命名空间中,其中包含更多的线程安全集合.

已处理所有项目,但并非所有项目都已添加到列表中.原因是,当两个线程试图在完全相同的时间添加不同的项时,list无法处理它,并且只保存其中一个.