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 BagStore<T>
: IConcurrentStore<T>
{
private readonly ConcurrentBag<T> Storage
= new ConcurrentBag<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.Add(data);
Interlocked.Increment(ref _Size);
OnItemAdded?.Invoke(this, data);
return _Size;
}
public bool TryTake(out T data)
{
if (Storage.TryTake(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);
}
}
}
}