gpt4 book ai didi

c# - 在 Linq 语句中使用 ConcurrentQueue

转载 作者:行者123 更新时间:2023-11-30 16:28:02 29 4
gpt4 key购买 nike

如果我有一个 ConcurrentQueue,是否有使用 Linq 语句的首选方法?它没有将所有项目作为序列出列的方法,并且它的枚举器不会删除项目。

我正在进行批量消费,这意味着我想定期处理队列并将其清空,而不是处理它直到它变空并阻塞直到更多项目入队。 BlockingCollection 似乎不起作用,因为它会在到达最后一项时阻塞,我希望该线程做其他事情,比如清除其他队列。

static ConcurrentQueue<int> MyQueue = new ConcurrentQueue<int>();
void Main()
{
MyQueue.Enqueue(1);MyQueue.Enqueue(2);MyQueue.Enqueue(3);MyQueue.Enqueue(4);MyQueue.Enqueue(5);

var lst = MyQueue.ToLookup(x => x.SomeProperty);
//queue still has all elements
MyQueue.Dump("queue");
}

现在,我做了一个辅助方法

static IEnumerable<T> ReadAndEmptyQueue<T>(this ConcurrentQueue<T> q)
{
T item;
while(q.TryDequeue(out item))
{
yield return item;
}
}

var lk = MyQueue.ReadAndEmptyQueue().ToLookup(x => x.SomeProperty);
MyQueue.Dump(); //size is now zero

是否有更好的方法,或者我做得对吗?

最佳答案

在我看来,你的做法非常合理。允许消费者以这种方式清空队列既干净又简单。

BlockingCollection doesn't seem like it will work because it will block when it gets to the last item, and I want that thread to do other stuff, like clear other queues.

我要提到的一件事 - 有时,从设计的角度来看,更容易为每个队列触发一个单独的消费者线程。如果你这样做,每个 BlockingCollection<T>可以只使用 GetConsumingEnumerable()并根据需要进行阻塞,因为当队列为空时它们将处于等待状态。

这是我更常采用的方法,因为从同步的角度来看,如果每个集合都有一个或多个专门的消费者,而不是消费者在其消费的内容之间切换,则通常要简单得多。

关于c# - 在 Linq 语句中使用 ConcurrentQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7368479/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com