Hello, here is my code section:

foreach(var process in Processes) { int SpendTime = QuantOfTime; foreach(var potok in process.Potoks) { if(potok.TimeOfOnePotok <= SpendTime) { potok.Start(); Console.WriteLine($"Поток №{potok.Id} {potok.Message}"); SpendTime -= potok.TimeOfOnePotok; process.Potoks.Remove(potok); } else { potok.Start(SpendTime); Console.WriteLine($"Поток №{potok.Id} {potok.Message}"); Processes.Add(process); break; } } } 

It gives an error that it is impossible to change the collection through a loop. What is better to replace the cycle or what is better to use in such cases?

  • And what's the point? Do you want to model a queue? Why add an item that is already there? - VladD
  • This is a classic; it is impossible to try to change the contents of a collection through a foreach . Want to play - use for . - Bulson 5:46
  • The meaning of the cycle is: until all the elements become valid, they will be added to the list, otherwise it will be deleted. The element is added modified, and it should be called after passing all the initial elements of the list. The result should have been a cyclical prediction algorithm in the OS, showing work with processes - Nikita Borgolov

2 answers 2

Changing an iterable collection in a foreach can lead to anomalies, such as endless loops.

If you want to change something, then iterate with your hands in a for loop.

    Apparently, you are modeling the queue. For this it is more convenient to use the queue, oddly enough. Your code will be as follows:

     Queue<Process> Processes; while (Processes.Count > 0) { var process = Processes.Dequeue(); if (...) { ... } else { ... Processes.Enqueue(process); } } 

    My code, unlike yours, removes the current item from the queue, but I think that’s what you need.