简体   繁体   English

如何清除/清空 c# 中的 BlockingCollection

[英]How to clear/empty BlockingCollection in c#

I have a thread which is adding items to a BlockingCollection.我有一个线程正在将项目添加到 BlockingCollection。 I want to clear the BlockingCollection.我想清除 BlockingCollection。 Can somebody help me with this?有人可以帮我吗?

You may need to read all the items from the BlockingCollection and assign to Discards您可能需要读取 BlockingCollection 中的所有项目并分配给Discards

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

Possibly use the overload of GetConsumingEnumerable that takes a CancellationToken;可能使用带 CancellationToken 的GetConsumingEnumerable的重载CancellationToken; then, if anything goes wrong from the producing side, it can cancel the consumer.然后,如果生产方出现任何问题,它可以取消消费者。

And you can use it你可以使用它

 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);
    }
}

And you can even use this site你甚至可以使用这个网站

Use ForEach to Remove Items in a BlockingCollection 使用 ForEach 删除 BlockingCollection 中的项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM