parallel foreach strange behavior

时间:2019-04-16 22:15:49

标签: c# parallel.foreach

I've code the runs more or less the following construct - and when ParallelRunner gets the delegate function testFunc it hangs , However if instead of providing a delegate I write the function explicitly inside the ParallelRunner method it works fine.

Note that this exact test method works, but a very similar code running under IIS ( in a background thread ) fails , and once I remove the testFunc delegate and explicitly write its code in ParallelRunner , or even call TestCondition directly ( without a delegate ) it works fine.

Any idea what could cause this strange behavior ?

  interface I { }

        class A : I { }
        class B :I { }

        [TestMethod]
        public void TestParallelWithDelegate()
        {
            var list = new List<I>();

            for (int i = 0; i < 300000; i++)
            {
                if (i % 2 == 0)
                {
                    list.Add(new A());

                }
                else
                {
                    list.Add(new B());
                }


            }

            var bag = new ConcurrentBag<I>();

            Func<I, bool> testFunc = TestCondition;

            ParallelRunner(list,bag,testFunc);

            Console.WriteLine($"terminated with delegate bag size = {bag.Count}");

        }
        private static bool TestCondition(I i)
        {
            return !(i is A);
        }


        void ParallelRunner(List<I> list, ConcurrentBag<I> bag, Func<I,bool> testFunc = null)
        {
            Parallel.ForEach(list, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 3 },
                x =>
                {
                    if (testFunc == null || testFunc(x))
                    {
                        bag.Add(x);

                    }
                });

        }

0 个答案:

没有答案