Syncronized Queue : Queue « Collections Data Structure « C# / C Sharp






Syncronized Queue

        
using System.Collections.Generic;
using System.Threading;

namespace Td.Additional.Collections
{
    /// <summary>
    /// Syncronized queue.
    /// See also: http://www.mycsharp.de/wbb2/thread.php?threadid=80713.
    /// </summary>
    /// <typeparam name="T">Type of queued items.</typeparam>
    public class SyncQueue<T>
    {
        #region Private fields

        private Queue<T> _q = new Queue<T>();

        #endregion

        #region Queue methods

        /// <summary>
        /// Enqueues the specified item.
        /// </summary>
        /// <param name="tItem">The item.</param>
        public void Enqueue(T tItem)
        {
            lock (this)
            {
                _q.Enqueue(tItem);
                Monitor.Pulse(this);
                System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.Name + " Enqueue ==> " + _q.Count);
            }
        }

        /// <summary>
        /// Dequeues the next item. If no item in queue, method waits, until an item is in the queue.
        /// </summary>
        /// <returns></returns>
        public T Dequeue()
        {
            Monitor.Enter(this);
            try
            {
                while (_q.Count == 0)
                {
                    System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.Name + " Wait");
                    Monitor.Wait(this);
                }
                System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.Name + " Dequeue ==> " + (_q.Count - 1));
                return _q.Dequeue();
            }
            finally
            {
                Monitor.Exit(this);
            }
        }

        #endregion
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Put elements into a queue
2.Put user-defined objects to Queue collection
3.Implements the queue data type using an arrayImplements the queue data type using an array
4.A queue class for charactersA queue class for characters
5.illustrates the use of a Queueillustrates the use of a Queue
6.Queue testQueue test
7.Add exception handling to the queue classesAdd exception handling to the queue classes
8.Demonstrate the Queue classDemonstrate the Queue class
9.Priority Queue
10.Queue(T) Class represents a first-in, first-out collection of objects.
11.Priority Queue (2)
12.Dequeue
13.Implements a non-locking queue
14.Task queue
15.Cyclic Queue