C
C#17mo ago
Mechno

❔ why is .ToList() considered being in a right answer for this problem?

Stack Overflow
Collection was modified; enumeration operation may not execute
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur. Collection was modified; enumeration operation may not execute Below is the code. This i...
11 Replies
ero
ero17mo ago
You linked an answer which says ToList isn't the right answer?
Moods
Moods17mo ago
The most-voted answer also explained why
Moods
Moods17mo ago
Omnissiah
Omnissiah17mo ago
yeah ToList would be a copy of the object for that thread but that's not a great solution because it could lead to a lot of copies and a lot of memory maybe a concurrent dictionary would be better or a lock or a soft delete it depends the immutable thing could also be good, a more formal approach
Mechno
MechnoOP17mo ago
Sorry i meant the answer with green check By tolist isnt thread safe or is it? The other thread could change the list while tolist is executing on other thread It just doesnt feel right that people would just go with that answer or maybe there is something that i am missing
Omnissiah
Omnissiah17mo ago
you can look at the source of ToList() by F12 it answer is 99% it's not therad safe
Moods
Moods17mo ago
i see what u mean ig you'd have to make it Immutable
Moods
Moods17mo ago
Stack Overflow
Collection was modified; enumeration operation may not execute
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur. Collection was modified; enumeration operation may not execute Below is the code. This i...
Mechno
MechnoOP17mo ago
but you can still call both methods at the same time which mean u you can access the 'subscribers' twice at the same time. Once when you are replacing it with new collection and second time when I guess foreach is getting reference to it?
Omnissiah
Omnissiah17mo ago
making the object immutable means that you can't write it so there could not be a shared writing error but yeah still all the other parts are not protected for thread-safeness
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server