Parallel.Foreach 问题

Joh*_*ers 5 c# task-parallel-library parallel.foreach

我有一个Parallel.Foreach循环让我感到悲伤,想看看你们中的一个人是否可以解释这一点。不幸的是,在谷歌上几乎找不到这个。

这是结:

我的 foreach 循环:

string [] Ids = {........}; //a string array of ID's
using(IUnitOfWork uw = GetUnitOfWork())
     {
            Parallel.ForEach(Ids, currentRecord =>
            {
                var x = (from h in uw.GetRepository<EFEntity1>().AsQueryable()
                         join k in uw.GetRepository<EFEntity2>().AsQueryable()
                         on h.ID equals k.ID
                         join l in uw.GetRepository<EFEntity3>().AsQueryable() on 
                          h.FundAccount equals l.FundAccount
                         where h.ID == currentRecord
                         select new { h.x, h.y, h.z});
                foreach (var v in x)
                {
                    if (v.SomeMember == "foo")
                    {

                    }
                    Console.WriteLine("Output : {0} {1} {2} {3} {4} ", v.x, 
                                      v.y, v.z);
                }
            });
        }
Run Code Online (Sandbox Code Playgroud)

LINQ 语句是我得到一个ArgumentExcpetion抛出的地方:

已添加具有相同密钥的项目

有什么线索可以说明我在这种情况下实现 foreach 循环可能出现的问题吗?

感谢您的支持。

谢谢

小智 4

我通过将 using 括号移动到并行循环中解决了这个问题。原因是因为 dbcontext 不是线程安全的。