zdimension
zdimension

Reputation: 1084

InvalidOperationException with foreach even though the collection is locked

Lately, I've been trying to make an old project of mine work using multiple threads, and obviously collections are part of the fun. The problem is that one bit of code keeps crashing randomly (not often but still noticeably enough):

enter image description here

Monde is a SynchronizedCollection, and I'm locking it to prevent simultaneous writes, but it's still complaining about it. Is there something I'm missing about it?

edit: I am aware that the SynchronizedCollection class only locks automatically during the creation of the Enumeration, hence a plain foreach isn't enough and that's why I'm enclosing the whole loop in a lock block. The problem is in the fact that the collection somehow gets modified while the thread is inside the lock block, which shouldn't happen.

Also, none of the classes under the .NET 4 concurrent API fulfill all my needs so I don't really have a choice if I don't want to make the whole codebase more complicated than it already is.

Upvotes: 0

Views: 186

Answers (1)

Siavash Rostami
Siavash Rostami

Reputation: 1933

First of all, if you're using SynchronizedCollection then you won't need to wrap it in lock because it does the operations with lock under the hood. And second SynchronizedCollection is from .Net 2.0 era, and if you're porting your legacy code then you'd better use collections from System.Collections.Concurrent namespace instead. They are newer, more optimized and don't rely on locking and blocking strategies.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent?redirectedfrom=MSDN&view=netframework-4.8

Upvotes: 1

Related Questions