【问题标题】:Enqueued event for Queue<T> in C#C# 中 Queue<T> 的入队事件
【发布时间】:2021-07-27 14:01:05
【问题描述】:

我是活动和代表的新手。如何为Queue&lt;T&gt; 类型的对象实现入队事件?

我正在使用 C# 和 .Net 4.0

【问题讨论】:

  • 由于Queue&lt;T&gt; 还没有这样的事件,并且所有操作方法(即入队、出队等)都是非虚拟的,因此您根本无法安全地在该类上提供此功能。您最好编写自己的 Queue 类来实现这些事件,并可能使用本机 Queue&lt;T&gt; 作为后备存储。

标签: c# .net events delegates .net-4.0


【解决方案1】:

您可以用自己的类封装 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;
        }
} 

【讨论】:

    【解决方案2】:

    System.Collections.* 类套件没有触发任何事件。由于您使用的是 .NET 4.0,因此您可能需要查看 BlockingCollection&lt;T&gt;,而不是依赖事件,而是使用 the Producer-Consumer pattern 从集合中获取从另一个线程到达的元素。 BlockingCollection&lt;T&gt; 将有效地为您处理所有线程安全和同步。

    BlockingCollection&lt;T&gt; 的默认支持类型是 ConcurrentQueue&lt;T&gt;,这听起来像是您想要的,但应该注意的是,如果您愿意/不介意,您可以将其更改为使用 ConcurrentStack&lt;T&gt;ConcurrentBag&lt;T&gt;不同的排序特征。

    BlockingCollection&lt;T&gt; 的另一个重要功能是set bounds 的功能,它可以帮助阻止生产者向集合中添加超出消费者能够跟上的项目。

    要获得关于这个主题各个方面的精彩文章,我建议查看 Alexeandra Rusina 的 this blog post。该帖子还介绍了使用 Task Parallel Library 处理 BlockingCollection 的方法。

    【讨论】:

    • 很少有人愿意使用不关心排序特征的队列。 ;)
    • 是的,当然看起来最初的问题对队列最感兴趣,但我只想指出 BlockingCollection 可以使用许多差异。后备商店。
    • 从未听说过 BlockingCollection!马上查。谢谢:)
    • +1 BlockingCollection 从来没有越过我的道路......现在交换我的实现!谢谢!
    • 因为那篇文章我 +1 了;写得非常好,一个很好的演示,不使用while(true)
    猜你喜欢
    • 2011-07-23
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2010-09-05
    • 2014-08-22
    • 2011-01-16
    相关资源
    最近更新 更多