[CHANGE] BackgroundServices
This commit is contained in:
56
Manager.App/Services/CircularBuffer.cs
Normal file
56
Manager.App/Services/CircularBuffer.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace Manager.App.Services;
|
||||
|
||||
public class CircularBuffer <T>
|
||||
{
|
||||
private readonly T[] _buffer;
|
||||
private readonly Channel<T> _channel;
|
||||
|
||||
public int Capacity { get; }
|
||||
public int Head { get; private set; }
|
||||
public int Count { get; private set; }
|
||||
|
||||
|
||||
public CircularBuffer(int capacity)
|
||||
{
|
||||
if (capacity <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
}
|
||||
|
||||
Capacity = capacity;
|
||||
_buffer = new T[Capacity];
|
||||
_channel = Channel.CreateUnbounded<T>(new UnboundedChannelOptions
|
||||
{
|
||||
SingleReader = false,
|
||||
SingleWriter = false,
|
||||
});
|
||||
}
|
||||
|
||||
public void Add(T item)
|
||||
{
|
||||
_buffer[Head] = item;
|
||||
Head = (Head + 1) % _buffer.Length;
|
||||
|
||||
if (Count < _buffer.Length)
|
||||
{
|
||||
Count++;
|
||||
}
|
||||
|
||||
_channel.Writer.TryWrite(item);
|
||||
}
|
||||
|
||||
public IEnumerable<T> Items
|
||||
{
|
||||
get
|
||||
{
|
||||
for (var i = 0; i < Count; i++)
|
||||
{
|
||||
yield return _buffer[(Head - Count + i + _buffer.Length) % _buffer.Length];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IAsyncEnumerable<T> GetStreamAsync() => _channel.Reader.ReadAllAsync();
|
||||
}
|
Reference in New Issue
Block a user