How to empty a BlockingCollection

≡放荡痞女 提交于 2020-01-12 13:34:10

问题


I have a thread adding items to a BlockingCollection .

On another thread I am using foreach (var item in myCollection.GetConsumingEnumerable())

If there is a problem I want to break out of my foreach and my method and clear whatever is left in the BlockingCollection however I can't find a way to do it.

Any ideas?


回答1:


Possibly use the overload of GetConsumingEnumerable that takes a CancellationToken; then, if anything goes wrong from the producing side, it can cancel the consumer.




回答2:


I'm using this extension method:

public static void Clear<T>(this BlockingCollection<T> blockingCollection)
{
    if (blockingCollection == null)
    {
        throw new ArgumentNullException("blockingCollection");
    }

    while (blockingCollection.Count > 0)
    {
        T item;
        blockingCollection.TryTake(out item);
    }
}

I'm wondering if there's a better, less hacky, solution.




回答3:


This worked for me

while (bCollection.Count > 0)
{
    var obj = bCollection.Take();
    obj.Dispose();
}

Take() removes from the collection and you can call any clean up on your object and the loop condition does not invoke any blocking calls.




回答4:


Just take out all remaining items:

while (collection.TryTake(out _)){}



回答5:


BlockingCollection<T> yourBlockingCollection = new BlockingCollection<T>();

I assumed you mean clear your blocking collection. Jon's answer is more appropriate to your actual question I think.




回答6:


For just clearing the collection you can do:

myBlockingCollection.TakeWhile<*MyObject*>(qItem => qItem != null);

or just

myBlockingCollection.TakeWhile<*MyObject*>(qItem => true);


来源:https://stackoverflow.com/questions/8001133/how-to-empty-a-blockingcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!