How can an item be rem开发者_开发问答oved from a BlockingCollection? Which of the following is correct?
myBlockingCollection.Remove(Item);
or
myBlockingCollection.Take(Item);
You can't specify a particular item to be removed from a BlockingCollection<T>.
The Take() method removes an item from the underlying collection and returns the removed item.
The TryTake(out T item) method removes an item from the underlying collection and assigns the removed item to the out parameter. The method returns true if an item could be removed; otherwise, false.
The item which is removed depends on the underlying collection used by the BlockingCollection<T> - For example, ConcurrentStack<T> will have LIFO behavior and ConcurrentQueue<T> will have FIFO behavior.
What about this code? - It's working but change the order of the collection. (And I didn't checked it in multi threads state).
public static bool Remove<T>(this BlockingCollection<T> self, T itemToRemove)
{
lock (self)
{
T comparedItem;
var itemsList = new List<T>();
do
{
var result = self.TryTake(out comparedItem);
if (!result)
return false;
if (!comparedItem.Equals(itemToRemove))
{
itemsList.Add(comparedItem);
}
} while (!(comparedItem.Equals(itemToRemove)));
Parallel.ForEach(itemsList, t => self.Add(t));
}
return true;
}
I think only TryTake() is an option? I can't find documention on the Remove() method on MSDN.
I think TryTake(out item) will work. Remove does not exist in BlockingCollection class and Take does not take item as parameter.
加载中,请稍侯......
精彩评论