For loops and foreach loops under Multithreading System.InvalidOperationException: The collection has been modified; enumeration may not be performed

Source: Internet
Author: User

Background: When the loop body is in circulation, there is a need to modify itself. or in multi-threaded, cyclic static variables, it is easy for others to modify the data in the loop body. But that's going to be an error.

Preparation: For;foeach; multithreading.

Solution: The For loop is thread-safe, and foreach is thread insecure. It seems to be very big on the open ha. Meaning within the loop as if they were calling their own loop body. The former is OK, but the latter is not.

And if you're looping through a dictionary. Dictionaries are the form of key-value pairs, so a dictionary of thread-safe dictionaries can also be used to concurrentdictionary a certain degree of problem solving. But a good solution is to add locks.

1, use for

2, using a secure set

3, with lock (most secure but impact performance)

Code results show:

using system;using system.collections.generic;using system.linq;using System.Text;            Namespace forandforeach{class Program {static void Main (string[] args) {//Integer list            list<int> listint = new list<int> ();            Listint.add (0);            Listint.add (1);            Listint.add (2);            Listint.add (3);            Listint.add (4);            Listint.add (5);                The For loop calls itself for (int i = 0; i < Listint.count; i++) {Console.WriteLine ("For:" +listint[i]);                Listint.add (6);                if (i = = 6) {break; }}//foreach loop calls itself foreach (int i in Listint) {Console.WriteLine ("Foreac                H: "+i");                Listint.add (7);                if (i = = 7) {break; }            }                    }    }}


For loops and foreach loops under Multithreading System.InvalidOperationException: The collection has been modified; enumeration may not be performed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.