Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an item from a BlockingCollection

Tags:

c#

collections

How can an item be removed from a BlockingCollection? Which of the following is correct?

myBlockingCollection.Remove(Item);

or

myBlockingCollection.Take(Item);
like image 678
Stacker Avatar asked Apr 14 '11 08:04

Stacker


2 Answers

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.

like image 88
Derek W Avatar answered Oct 13 '22 01:10

Derek W


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;
    }
like image 41
Binygal Avatar answered Oct 12 '22 23:10

Binygal