none
Collection was modified , enumeration operation may not execute. RRS feed

  • Question

  • I am getting this error , not sure why this error is occurring . Could you please help.

    var carrierList = GetAllCarriersForInputRecords(orgService, importedEnrollments);

                var options = new ParallelOptions() { MaxDegreeOfParallelism = maxThreads };
                //Loop Through Record Keeper Records
                ConcurrentBag<ImportedEnrollmentStatus> enrollmentList = new ConcurrentBag<ImportedEnrollmentStatus>(importedEnrollments);
                Parallel.ForEach(enrollmentList, options, () => { return GetOrgServiceProxy(_orgServiceManagement, _authCredentials); },
                (enrollmentStatus, loopState, index, threadProxy) =>
                {
                    threadProxy.EnableProxyTypes();
                    var orgThreadProxy = GetOrgServiceProxy(_orgServiceManagement, _authCredentials);
                    orgThreadProxy.EnableProxyTypes();

                    var currentOutput = new JobProcessOutputStatus(true);
                    var logic = new ValidationLogic(orgThreadProxy);


                    try
                    {
                        //if we get an actual error, we don't want the entire process to quit
                        currentOutput = logic.ValidateImportedEnrollmentStatus(enrollmentStatus, carrierList, jobTracking, currentOutput.RowCount, currentOutput.TotalSuccess);

                        Interlocked.Add(ref totalProcessed, 1);
                        Interlocked.Add(ref totalSuccess, currentOutput.Success ? 1 : 0);
                        Log.InfoFormat("{0}. Processed {1} {2}\n", totalProcessed, enrollmentStatus.exch_FirstName, enrollmentStatus.exch_LastName);
                    }
                    catch (Exception e)
                    {
                        exceptions.Enqueue(e);

                        logic.UpdateLogic.AddProcessingNote("9000", string.Format("Processing Ended With an Error: {0}", e.Message), (int)exch_processingnoteseverity._300ErrorOverridable, enrollmentStatus);

                        currentOutput.Success = false;
                    }

                    if (totalProcessed % jobUpdateIncrement == 0)
                    {
                        jobFileTracking.UpdateJobFileTracking(orgService, false, totalProcessed, totalSuccess, totalProcessed - totalSuccess);
                        jobTracking.UpdateJobTrackingErrorCounts(orgService, totalProcessed - totalSuccess);
                    }

                    //return proxy to the next iteration in the current thread's loop 
                    return orgThreadProxy;
                },
                threadProxy => threadProxy.Dispose());

                jobFileTracking.UpdateJobFileTracking(orgService, true, totalProcessed, totalSuccess, totalProcessed - totalSuccess);
                jobTracking.UpdateJobTrackingErrorCounts(orgService, totalProcessed - totalSuccess);

                if (exceptions.Count > 0)
                    throw new AggregateException(exceptions);

            }

    Tuesday, March 3, 2020 11:09 AM

All replies

  • Use the debugger to pinpoint the exact line of code where you are getting the error. This error happens inside a foreach loop when the loop modifies the very collection that it is looping on. Such a loop is not directly visible in your code, but your code calls many subroutines and it is possible that one of these subroutines contains a foreach that modifies its collection.
    Tuesday, March 3, 2020 12:19 PM
    Moderator
  • Hello,

    The error indicates that while looping (foreach) through the collection something was modified as the exception indicates which you can not do, so a refactor would be in order such as a for-next which will not have this problem done in a foreach.

    So for instance adding to the collection would be an issue in a foreach.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, March 3, 2020 12:21 PM
    Moderator
  • Hi Priya0867,

    Thank you for posting here.

    Because you have a lot of custom classes and methods in your code, I can't reproduce this problem with your code, but in general, this problem occurs in foreach, I wrote a simple code example.

         class Program
        {
            static void Main(string[] args)
            {
                List<MyClass> list = new List<MyClass>();
                list.Add(new MyClass() { Name = "test1"});
                list.Add(new MyClass() { Name = "test2" });
                list.Add(new MyClass() { Name = "test3" });
                list.Add(new MyClass() { Name = "test4" });
    
                foreach (var item in list)
                {
                    if (item.Name=="test2")
                    {
                        list.Add(new MyClass()); 
                    }
                }
            }
        }
        class MyClass
        {
            public string Name { get; set; }
        }

    If you want to solve this problem, just copy the collection to another collection, so that the modified and enumerated are not the same collection.

    In my case, all I need to do is modify the code to look like this.

                foreach (var item in list.ToArray())
                {
                    if (item.Name=="test2")
                    {
                        list.Add(new MyClass()); 
                    }
                }

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    Wednesday, March 4, 2020 2:20 AM
  • Hi,

    Has your problem been solved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 11, 2020 9:25 AM