c#:队列的入队事件
我是活动和代表的新手。 你能否指出我为Queue 类型的对象实现Enqueued事件的正确方向?
我正在使用C#和.Net 4.0
谢谢
您可以使用自己的类封装Queue类,例如:
class MyQueue { private readonly Queue queue = new Queue (); public event EventHandler Enqueued; protected virtual void OnEnqueued() { if (Enqueued != null) Enqueued(this, EventArgs e); } public virtual void Enqueue(T item) { queue.Enqueue(item); OnEnqueued(); } public int Count { get { return queue.Count; } } public virtual T Dequeue() { T item = queue.Dequeue(); OnEnqueued(); return item; } }
HTH!
System.Collections。*套件类没有触发任何事件。 由于您使用的是.NET 4.0,因此您可能需要查看BlockingCollection
,而不是依赖于事件,您将使用Producer-Consumer模式从集合中获取元素,因为它们是从另一个线程到达的。 BlockingCollection
将有效地处理所有线程安全和同步。
BlockingCollection
的默认支持类型是ConcurrentQueue
,它听起来像你想要的,但应该注意你可以改变它以使用ConcurrentStack
或ConcurrentBag
如果你想要/不注意不同的排序特征。
BlockingCollection
另一个重要特性是能够设置边界 ,这可以帮助阻止生产者向集合中添加比消费者可以跟上的更多项目。
为了对这个主题的各个方面进行精彩的写作,我建议您查看来自Alexeandra Rusina的这篇博客文章 。 该文章还介绍了使用任务并行库使用BlockingCollection的方法。