4

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.

4

3 回答 3

8

你试过ConcurrentDictionary吗?它有一个TryRemove方法,因此如果您将键视为谓词,那么您将删除正确的项目。

于 2012-02-29T21:15:08.337 回答
5

你确定ConcurrentQueue<T>不符合你的需求?它有一个TryPeek方法和一个TryDequeue完全按照您在上一段中描述的方法。

于 2012-02-29T21:14:51.007 回答
1

这里的其他答案不直接回答问题,或提供可能不受欢迎的限制。例如,ConcurrentDictionary 使用键来防止添加重复实例。

SynchronizedCollection 似乎是需要的,因为它是线程安全的并且包含一个 Remove 方法。

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

代码示例:

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

FilePathsToIgnore.Add(someFileName);
...

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


于 2021-07-09T13:46:26.307 回答