Queue的入队事件在 C# 中
我是活动和代表的新手。如何为 Queue
类型的对象实现排队事件?
我正在使用 C# 和 .Net 4.0
I am new to event and delegates. How can I implement an enqueued event for an object of type Queue<T>
?
I am using C# and .Net 4.0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以用自己的类封装 Queue 类,例如:
You can encapsulate the Queue class with your own class, something like:
System.Collections.* 类套件没有触发任何事件。由于您使用的是 .NET 4.0,因此您可能需要查看
BlockingCollection
而不是依赖事件,您可以使用 生产者-消费者模式,用于在元素从另一个线程到达时从集合中获取元素。BlockingCollection< ;T>
将有效地为您处理所有线程安全和同步。BlockingCollection
是ConcurrentQueue
这听起来像你想要的,但应该注意的是,你可以将其更改为使用ConcurrentStack;
或ConcurrentBag
如果您想要/不介意不同的排序特征。的另一个很棒的功能
BlockingCollection
能够设置界限,这可以帮助阻止生产者向集合中添加超出消费者可以跟上的项目。要获得有关该主题各个方面的精彩文章,我建议查看 这篇博文来自 Alexeandra Rusina。这篇文章还介绍了使用 任务并行库 来使用 BlockingCollection 的方法。
There are no events fired from the System.Collections.* suite of classes. Since you're using .NET 4.0, you may want to look into
BlockingCollection<T>
instead which, instead of relying on events, you would use the Producer-Consumer pattern to Take elements from the collection as they arrive from another thread.BlockingCollection<T>
will take care of all thread-safety and synchronization for you efficiently.The default backing type for
BlockingCollection<T>
isConcurrentQueue<T>
which sounds like what you want, but it should be noted that you can change it to use aConcurrentStack<T>
orConcurrentBag<T>
if you want/don't mind different ordering characteristics.Another great feature of
BlockingCollection<T>
is the ability to set bounds which can help block the producer from adding more items to the collection than the consumers can keep up with.For a great write up on all aspects of this subject, I suggest checking out this blog post from Alexeandra Rusina. The post also covers ways to work with BlockingCollection using the Task Parallel Library.