views:

64

answers:

2

Hello,

I am new to event and delegates. Could you point me to the right direction for implementing Enqueued event for an object of type Queue<T>?

I am using C# and .Net 4.0

Thanks

+4  A: 

You can encapsulate the Queue class with your own class, something like:

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;
        }
} 

HTH!

Dienekes
+1, yup, perfect. Thanks for typing that all out. ;)
Kirk Woll
+1 Perfect indeed. Thanks a lot :)
Ruby
+3  A: 

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> is ConcurrentQueue<T> which sounds like what you want, but it should be noted that you can change it to use a ConcurrentStack<T> or ConcurrentBag<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.

Drew Marsh
@Drew, it's the rare soul who wants to use a queue that doesn't care about ordering characteristics. ;)
Kirk Woll
Yes of course it would seem the original question was most interested in a queue, but I just wanted to point out that BlockingCollection can use many diff. backing stores.
Drew Marsh
Never heard of BlockingCollection!! Looking it up right now. Thanks :)
Ruby
+1 BlockingCollection never crossed my path... exchanging my implementation right now! Thanks!
Mario The Spoon