John-Anders
John-Anders

Reputation: 121

Parallel.Foreach issue

I have a Parallel.Foreach loop that is giving me grief, and wanted to see if one of you guys could shed some light on this. Little to be found googling this unfortunately.

Here is the knot:

My foreach loop :

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);
                }
            });
        }

The LINQ statement is where I get an ArgumentExcpetion thrown saying:

An item with the same key has already been added

Any clues to what might be wrong with my implemntation of the foreach loop in this scenario?

Appreciate the support.

Thanks

Upvotes: 5

Views: 1797

Answers (1)

DB CC
DB CC

Reputation: 64

I resolved this with moving the using bracket into the Parellel loop. Reason was because the dbcontext is not thread-safe.

Upvotes: 4

Related Questions