Reputation: 14379
I need to be able to enumerate the collection in any order (foreach) and Add/Remove an item from any thread.
Direct access by index is not needed.
What collection do I use? Simply a List? If so, do I only have to lock on add/remove or do I have to lock on foreach also?
I want the following operations to be available on any thread.
foreach (var item in myCollection)
{
// myCollection can be returned in any order.
}
myCollection.Add(item)
var success = myCollection.Remove(item) // returns false if the item does not exist in myCollection
Upvotes: 0
Views: 101
Reputation: 23626
You sould use ConcurrentBag for thread-safe collections, which Represents a thread-safe, unordered collection of objects
, which is avaliable since .NET 4.0
note: I can't give more information because I'm not aware of the context, in which you are going to use it. Provide more information for a deeper answer.
Upvotes: 4