With the new ConcurrentBag
in .NET 4, how do you remove a certain, specific object from it when only TryTake()
and TryPeek()
are
This is my extension class which I am using in my projects. It can a remove single item from ConcurrentBag and can also remove list of items from bag
public static class ConcurrentBag
{
static Object locker = new object();
public static void Clear(this ConcurrentBag bag)
{
bag = new ConcurrentBag();
}
public static void Remove(this ConcurrentBag bag, List itemlist)
{
try
{
lock (locker)
{
List removelist = bag.ToList();
Parallel.ForEach(itemlist, currentitem => {
removelist.Remove(currentitem);
});
bag = new ConcurrentBag();
Parallel.ForEach(removelist, currentitem =>
{
bag.Add(currentitem);
});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public static void Remove(this ConcurrentBag bag, T removeitem)
{
try
{
lock (locker)
{
List removelist = bag.ToList();
removelist.Remove(removeitem);
bag = new ConcurrentBag();
Parallel.ForEach(removelist, currentitem =>
{
bag.Add(currentitem);
});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}