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