Sean Thoman
Sean Thoman

Reputation: 7489

Thread safe collection that supports removing items

I cannot seem to find a .NET thread safe / concurrent collect that supports a simple Remove() function where I can either remove a specific item or pass in a predicate to remove items based on that. I have tried:

BlockingCollection<T>
ConcurrentQueue<T>
ConcurrentStack<T>
ConcurrentBag<T>

Does anyone know of a collection that supports this behavior, or do I have to create my own?

I want to be able to grab the next item from a thread-safe queue without removing it, and later on if a certain condition is met, proceed with removing it.

Upvotes: 4

Views: 7362

Answers (3)

Victor Chelaru
Victor Chelaru

Reputation: 4837

The other answers here do not directly answer the question, or provide limitations which may be undesirable. For example, ConcurrentDictionary uses keys preventing duplicate instances from being added.

SynchronizedCollection seems to be what is needed as it is thread-safe and contains a Remove method.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.synchronizedcollection-1?view=dotnet-plat-ext-5.0

Code example:

SynchronizedCollection<string> FilePathsToIgnore = new SynchronizedCollection<string>();
...

FilePathsToIgnore.Add(someFileName);
...

if(FilePathsToIgnore.Contains(fileName))
{
    FilePathsToIgnore.Remove(fileName);
}


Upvotes: 1

Kiril
Kiril

Reputation: 40345

Have you tried ConcurrentDictionary? It has a TryRemove method, so if you think of the key as a predicate, then you will be removing the correct item.

Upvotes: 8

Thomas Levesque
Thomas Levesque

Reputation: 292465

Are you sure ConcurrentQueue<T> doesn't suit your needs? It has a TryPeek method and a TryDequeue method that do exactly what you describe in the last paragraph.

Upvotes: 5

Related Questions