locked
Collection was modified; enumeration operation may not execute. RRS feed

  • Question

  • Getting this exception for the following code:

    privatestring Tags=null;

    privatestaticList<string> TagsCollection=newList<string>();

    static void main()

    {

    foreach (string temp in Tags.Split(';')) {

    TagsCollection.Add(temp);

    }

    if (SomeCollection.OfType<Somethingelse>()
    .Any(x => TagsCollection.Contains(x.tag, StringComparer.OrdinalIgnoreCase))) Console.Write(true);


    }

    I am trying to find cause for such an exception here. I suspect if it can only in multithreaded environment.

    Thanks for your help,

    Sowjanya




    Friday, July 12, 2019 9:03 AM

All replies

  • I suspect the error is because the collection is getting modified in another thread.  The two ways you can fix is it is by using a lock statement or clone object the loop through the clone

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement

    https://csharp2ae.blogspot.com/2017/03/cloning-object-in-pcl.html

    Monday, July 15, 2019 12:47 AM
  • Hi sowjanyaboddeti, 

    Thank you for posting here.

    As Ken Tucker suggested, the problem may be caused by other threads which has modified values of collection in for-each. You should avoid any changes to collections when using for-each.

    Try to use for statement instead of foreach statement, here’s the code:

                string[] tagsSplit = Tags.Split(';');
                for (int i=0;i< tagsSplit.Length;i++)
                {
                    TagsCollection.Add(tagsSplit[i]);
                    Console.WriteLine(tagsSplit[i]);
                }

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    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.

    Monday, July 15, 2019 8:53 AM