Untitled

 avatar
user_2299906
plain_text
a year ago
2.3 kB
1
Indexable
Never
public class MyQueue<T>
    {
        private Queue<T> queue = new Queue<T>();
        private AutoResetEvent signal = new AutoResetEvent(false);
        private object padLock = new object();
        Random rd = new Random(Guid.NewGuid().GetHashCode());
        public MyQueue(List<T> lists = null)
        {
            if (lists != null) queue = new Queue<T>(lists);           
        }
        public void Enqueue(T item)
        {
            lock (padLock)
            {
                queue.Enqueue(item);
                signal.Set();
            }
        }
        public void Remove(T item)
        {
            lock (padLock)
            {
                queue = RemoveAt(item);
                signal.Set();
            }
        }
        private Queue<T> RemoveAt(T item)
        {
            Queue<T> tmp = new Queue<T>();
            foreach(T s in queue)
            {
                if (!s.Equals(item)) tmp.Enqueue(s);
            }
            return tmp;
        }
        public int Count()
        {
            lock (padLock)
            {
                return queue.Count();
            }
            
        }
        public T Peek()
        {
            lock (padLock)
            {
                if (queue.Count < 1)
                {
                    return default(T);
                }
                return queue.Peek();
            }
        }
        public T GetRandom()
        {            
            try
            {
                lock (padLock)
                {
                    if (queue.Count < 1)
                    {
                        return default(T);
                    }
                    return queue.ElementAtOrDefault(rd.Next(0, queue.Count()));
                }
            }
            catch { return default(T); }
            
        }
        

        public T Dequeue()
        {
            try
            {
                lock (padLock)
                {
                    if (queue.Count < 1)
                    {
                        return default(T);
                    }
                    return queue.Dequeue();
                }
            } catch { return default(T); }
        }
    }