Die*_*kes 16
您可以使用自己的类封装Queue类,例如:
class MyQueue<T>
{
private readonly Queue<T> queue = new Queue<T>();
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;
}
}
Run Code Online (Sandbox Code Playgroud)
HTH!
System.Collections.*套件类没有触发任何事件.由于您使用的是.NET 4.0,因此您可能需要查看BlockingCollection<T>哪个,而不是依赖于事件,您将使用Producer-Consumer模式从集合中获取元素,因为它们从另一个线程到达.BlockingCollection<T>将有效地处理所有线程安全和同步.
默认后盾类型BlockingCollection<T>是ConcurrentQueue<T>这听起来像你想要什么,但应注意的是,你可以改变它使用一个ConcurrentStack<T>或者ConcurrentBag<T>,如果你想/不介意不同的排序特性.
另一个很棒的功能BlockingCollection<T>是能够设置边界,这可以帮助阻止生产者向集合中添加比消费者可以跟上的更多项目.
为了对这个主题的各个方面进行精彩的写作,我建议您查看来自Alexeandra Rusina的这篇博客文章.该帖子还介绍了使用任务并行库使用BlockingCollection的方法.