C# preventing Collection Was Modified exception

前端 未结 10 1939
梦毁少年i
梦毁少年i 2021-01-17 17:16

Does

 foreach(T value in new List(oldList) )

is dangerous (costly) when oldList contains 1 millions of object T ?

More g

10条回答
  •  猫巷女王i
    2021-01-17 18:16

    If you mean you can add/remove objects from another thread, I would: 1-synchronize the threads 2- in the add/remove threads, create a list of items to be added or deleted 3- and then delete these items in a critical section (so it is small - you don't have to synch while adding the items to the delete list)

    If you dont want to do that, you can use for instead of foreach, that would avoid the exception, but you would have to take extra care so you do not get other kinds of exceptions

提交回复
热议问题