C#: Triggering an Event when an object is added to a Queue

前端 未结 4 1079
别跟我提以往
别跟我提以往 2020-11-29 02:13

I need to be able to trigger a event whenever an object is added to a Queue.

I created a new class that extends Q

4条回答
  •  没有蜡笔的小新
    2020-11-29 02:29

    If you mean the non-generic Queue class, then you can just override Enqueue:

    public override void Enqueue(object obj)
    {
        base.Enqueue(obj);
        OnChanged(EventArgs.Empty);
    }
    

    However, if you mean the generic Queue class, then note that there is no suitable virtual method to override. You might do better to encapsulate the queue with your own class:

    (** important edit: removed base-class!!! **)

    class Foo
    {
        private readonly Queue queue = new Queue();
        public event EventHandler Changed;
        protected virtual void OnChanged()
        {
            if (Changed != null) Changed(this, EventArgs.Empty);
        }
        public virtual void Enqueue(T item)
        {
            queue.Enqueue(item);
            OnChanged();
        }
        public int Count { get { return queue.Count; } }
    
        public virtual T Dequeue()
        {
            T item = queue.Dequeue();
            OnChanged();
            return item;        
        }
    }
    

    However, looking at your code, it seems possible that you are using multiple threads here. If that is the case, consider a threaded queue instead.

提交回复
热议问题