且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 ConcurrentQueue 处理线程<T>

更新时间:2022-05-15 15:32:10

根据我对问题的理解,您遗漏了一些东西.

From my understanding of the problem, you are missing a few things.

并发队列是一种数据结构,旨在接受多个线程读取和写入队列,而无需显式锁定数据结构.(所有爵士乐都在幕后处理,或者集合以不需要锁定的方式实现.)

The concurrent queue is a data structure designed to accept multiple threads reading and writing to the queue without you needing to explicitly lock the data structure. (All that jazz is taken care of behind the scenes, or the collection is implemented in such a way that it doesn't need to take a lock.)

考虑到这一点,您尝试使用的模式似乎是生产者/消费者".首先,您有一些任务产生工作(并将项目添加到队列中).其次,您还有第二个任务消耗队列中的东西(并从队列中取出项目).

With that in mind, it looks like the pattern you are trying to use is the "Produce/Consumer". First, you have some tasks producing work (and adding items to the queue). And second you have a second task Consuming things from the queue (and dequeing items).

所以你真的需要两个线程:一个添加项目,第二个删除项目.因为您使用的是并发集合,所以可以有多个线程添加项目和多个线程删除项目.但显然,并发队列上的争用越多,就会越快成为瓶颈.

So really you want two threads: one adding items and a second removing items. Because you are using a concurrent collection, you can have multiple threads adding items and multiple threads removing items. But obviously the more contention you have on the concurrent queue the quicker that will become the bottleneck.