wasSharp – Rev 55

Subversion Repositories:
Rev:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Concurrent;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;

namespace wasSharp.Collections.Specialized
{
    /// <summary>
    /// The observable concurrent queue.
    /// </summary>
    /// <typeparam name="T">
    /// The content type
    /// </typeparam>
    public sealed class ObservableConcurrentQueue<T> : ConcurrentQueue<T>, INotifyCollectionChanged
    {
        public event NotifyCollectionChangedEventHandler CollectionChanged;

        private new void Enqueue(T item) 
        {
            EnqueueAsync(item).RunSynchronously();
        }

        public async Task EnqueueAsync(T item) => await Task.Run(() =>
            {
                base.Enqueue(item);

                OnCollectionChanged(
                    new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
            });

        private new bool TryDequeue(out T result)
        {
            result = DequeueAsync().Result;
            if (result.Equals(default(T)))
                return false;

            return true;
        }

        public async Task<T> DequeueAsync() => await Task.Run(() =>
            {
                if (!base.TryDequeue(out T item))
                    return default(T);

                OnCollectionChanged(
                    new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));

                return item;
            });

        public async Task<T> PeekAsync() => await Task.Run(() =>
        {
            if (!base.TryPeek(out T item))
                return default(T);

            return item;
        });

        private new bool TryPeek(out T result)
        {
            result = PeekAsync().Result;

            if (result.Equals(default(T)))
                return false;

            return true;
        }

        private void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
        {
            CollectionChanged?.Invoke(this, args);
        }


        public async Task Clear()
        {
            while (!base.IsEmpty)
                await DequeueAsync();
        }
    }
}

Generated by GNU Enscript 1.6.5.90.