Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.8 kB
2
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 AddRange(List<T> listitems)
        {            
            lock (padLock)
            {
                foreach (T item in listitems) 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); }
        }
        public List<T> ToList()
        {
            try
            {
                lock (padLock)
                {
                    return queue.ToList();
                }
            }
            catch { return default; }
        }
    }