BlockingCollection or Queue<T> for jobs?

心已入冬 提交于 2020-01-02 01:30:11

问题


I am developing a windows forms application ( c# ), and while program is running, it creates objects adds them to a list. I have to process the items in the list , with FIFO ( first in first out ). I want to do this in a backgroundthread and i have to process them in order, number 1 , number 2, number 3 and so on. And as soon as an item gets added to the list i want to process it. So i have to have something to check that list.

What is the best way to achieve this?

I know that blockingcollection does something similar, that it waits for an item to be added before processing it.

I can use a single thread with the Queue and just while(true) and take items if there is any?

What do you think?


回答1:


Sounds like you should go for the BlockingCollection<T> if you're planning on using a background thread. You can pretty easily do the same while(true) logic that you're looking for.

The BlockingCollection<T> gives you two important features

  1. It's thread-safe

  2. When you call Take(), it will block(i.e. wait until something is in the queue) for you, so you don't have to write any code with ManualResetEvents and the like, which is a nice simplification.




回答2:


IF you want to block if the queue is empty then use BlockingCollection - it is ideal... IF you want it more Queue-like (decide yourself how to deal with an empty) then ConcurrentQueue.

Both are thread-safe, in ConcurrentQueue most operations are implemented lock-free so really fast... either way use it directly or as the base type for your BlockingCollection for example BlockingCollection<string> = new BlockingCollection<string> (new ConcurrentQueue<string>) - you can even put a maximum capactiy on that (optional second param of constructor).



来源:https://stackoverflow.com/questions/7161104/blockingcollection-or-queuet-for-jobs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!