BlockingCollection或Queue< T>工作? [英] BlockingCollection or Queue<T> for jobs?

查看:57
本文介绍了BlockingCollection或Queue< T>工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Windows窗体应用程序(c#),并在程序运行时创建对象,将其添加到列表中。我必须使用FIFO(先进先出)处理列表中的项目。我想在backgroundthread中执行此操作,我必须按顺序处理它们,编号1、2、3等。并且,一旦将一个项目添加到列表中,我就想对其进行处理。因此,我必须要检查该列表。

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?

我知道blockingcollection会执行类似的操作,它会等待

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

我可以将单个线程与Queue一起使用,而while(true)可以使用,如果有的话可以拿走物品?

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

您怎么看?

推荐答案

听起来像您应该去的地方 BlockingCollection< T> 如果您打算使用后台线程。您可以轻松地执行所需的 while(true)逻辑。

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.

BlockingCollection< T> 为您提供了两个重要功能

The BlockingCollection<T> gives you two important features


  1. 它是线程安全的

  1. It's thread-safe

调用 Take() ,它将为您阻塞(即等待队列中有东西),因此您不必使用< a href = http://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent.aspx rel = noreferrer> ManualResetEvents 等,这是一个很好的简化。

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.

这篇关于BlockingCollection或Queue&lt; T&gt;工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆