How to empty a BlockingCollection

前端 未结 6 2240
闹比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 22:03

    I'm using this extension method:

    public static void Clear(this BlockingCollection 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.

提交回复
热议问题