C# preventing Collection Was Modified exception

前端 未结 10 1897
梦毁少年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条回答
  •  既然无缘
    2021-01-17 18:15

    It will be 'slow' but there is not much more you can do about it, except running it on a background thread. E.g. using a BackgroundWorker.

    If your operations on the list only occur on one thread, the correct approach is to add the items to add/remove to seperate lists, and perform those operations after your iterations has finished.

    If you use multiple threads you will have to look into multithreaded programming, and e.g. use locks or probably better a ReaderWriterLock.

    UPDATE: As mentioned in another Stack Overflow question, this is now possible without any effort in .NET 4.0 when using concurrent collections.

提交回复
热议问题