There is a class of the world in which the dictionary of life forms is located. Every Update in the world class is called foreach, which goes through all life forms and performs some actions with them (changing the bot fields, executing their methods, etc.)

Also, in the foreach cycle, new life forms can be created, their removal and entry of new ones into the enumerated dictionary (!)

You can see the code below (greatly simplified):

public class LifeForm { // реализация класса формы жизни } public class World { Dictionary<long, LifeForm> LifeForms; private void Update() { foreach (LifeForm bot in LifeForms.Values.ToList()) { // обновление данных бота,создание и добавление новых ботов в наш Dictionary } } } 

One iteration of foreach passes quickly and takes approximately 1-2ms. But with 10,000+ life forms in the dictionary, it takes more than 5 seconds to update it.

In itself, updating the dictionary in a single iteration foreach requires very few resources, is it possible to update several LifeForms elements at the same time? What can replace the classic foreach, so that the iteration occurs in several threads?

Parallel.ForEach does not give the desired effect, it works much slower with it

  • Use ConcurrentDictionary ? - Alexander Petrov
  • which collection has been modified? - Igor
  • @Igor LifeForms Dictionary - deced
  • Does LifeForms.Values.ToList() not create a new list? Do you have any other relevant code that is not shown in the question? - Igor
  • @Igor Well, there are methods in which this dictionary changes, but they are all called outside the Update world. - deced

0