How to empty a BlockingCollection

前端 未结 6 2235
闹比i
闹比i 2021-02-18 21:34

I have a thread adding items to a BlockingCollection .

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

相关标签:
6条回答
  • 2021-02-18 21:47
    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.

    0 讨论(0)
  • 2021-02-18 21:48

    For just clearing the collection you can do:

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

    or just

    myBlockingCollection.TakeWhile<*MyObject*>(qItem => true);
    
    0 讨论(0)
  • 2021-02-18 22:01

    Just take out all remaining items:

    while (collection.TryTake(out _)){}
    
    0 讨论(0)
  • 2021-02-18 22:02

    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.

    0 讨论(0)
  • 2021-02-18 22:03

    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.

    0 讨论(0)
  • 2021-02-18 22:09

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

    0 讨论(0)
提交回复
热议问题