Parallel.ForEach 在最终迭代期间冻结

Parallel.ForEach Freezing during final iterations

这是我第一次使用 Parrllel.ForEach,我遇到了一个问题。很遗憾,因为我真的需要这个程序的性能,而我正在得到它。

我会说在最后一次迭代中我的 ForEach 冻结了。这不会暴露任何错误消息。 ConsoleWriteLine() 停止了。当我在调试器中暂停时,Parallel.ForEach 的范围会突出显示。

   using (DBDataContext db = DataContextFactory.GetThreadScopedDataContext<DBDataContext>())
            {
                products = (from r in db.tbl_products
                           where r.date >= _dateCheck
                           select r

                ).ToList();

                int rcount = products.Count();

                Console.WriteLine("Total products: {0}", rcount);

                Parallel.ForEach(products, new ParallelOptions { MaxDegreeOfParallelism = 8 }, product =>
                {
                    DBDataContext db2 = DataContextFactory.GetThreadScopedDataContext<DBDataContext>();


                    CheckInventory(product, db2);


                });

                Console.WriteLine("Ended Inventory Check {0}", DateTime.Now);
            }

CheckInventory() 方法的最后阶段是创建匹配记录

  private static void AddNewInventoryMatch(tbl_product product, tbl_inventory item, int matchType)
        {


            DBDataContext db = DataContextFactory.GetThreadScopedDataContext<DBDataContext>("4");

            tbl_inventoryMatch newMatch = new tbl_inventoryMatch();
          //... Add records



            db.tbl_inventoryMatches.InsertOnSubmit(newMatch);
            //  db.SubmitChanges();


        }

我已经在整个网络上进行了搜索,试图找到可能导致此问题的原因,但我没有运气。这是一个简单的控制台应用程序,每晚 运行。

同样在它锁定后 VS 无法编译项目,除非我重新启动 VS。我收到此错误消息。

Error   11  Could not copy "obj\x86\Debug\Inventory-Match.exe" to "bin\Debug\Inventory-Match.exe". Exceeded retry count of 10. Failed.  Inventory-Match
Error   12  Unable to copy file "obj\x86\Debug\Inventory-Match.exe" to "bin\Debug\Inventory-Match.exe". The process cannot access the file 'bin\Debug\Inventory-Match.exe' because it is being used by another process. Inventory-Match

链接: DataContextFactory = http://weblog.west-wind.com/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management

我很久以前遇到过同样的问题,请尝试使用 GetDataContext 而不是 GetThreadScopedDataContext