StackStore.cs

71 lines | 1.469 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Collections.ObjectModel;

namespace Tools.Collections.Concurrent.AsyncBuffer.Store
{

    public class StackStore<T>
        : IConcurrentStore<T>
    {
        private readonly ConcurrentStack<T> Storage
            = new ConcurrentStack<T>();

        private int _Size;

        public event Action<IConcurrentStore<T>, T> OnItemAdded;
        public event Action<IConcurrentStore<T>> OnEmpty;

        public int Size
            => _Size;

        public int Add(T data)
        {
            Storage.Push(data);
            Interlocked.Increment(ref _Size);
            OnItemAdded?.Invoke(this, data);

            return _Size;
        }

        public bool TryTake(out T data)
        {
            if (Storage.TryPop(out data))
            {
                Interlocked.Decrement(ref _Size);

                if (_Size == 0)
                {
                    OnEmpty?.Invoke(this);
                }

                return true;
            }

            return false;
        }

        public IEnumerable<T> AsIEnumerable()
        {
            return Storage;
        }

        public void ForEach(Action<T> action)
        {
            foreach (var elem in Storage)
            {
                action(elem);
            }
        }
    }

    
}