using System.Collections.Generic;
public class CircularBuffer<T>
private readonly ReaderWriterLockSlim slimLock = new ReaderWriterLockSlim();
private readonly int capacity;
private readonly T[] buffer;
private readonly int upperBound;
private int currentIndex = -1;
private int currentStart = 0;
public CircularBuffer(int size)
throw new ArgumentException("Cannot be negative nor zero");
slimLock.EnterWriteLock();
if (IsFull || currentIndex == upperBound)
currentStart = FetchNextSlot(currentStart);
currentIndex = FetchNextSlot(currentIndex);
buffer[currentIndex] = value;
slimLock.ExitWriteLock();
public bool IsFull { get; private set; }
private int FetchNextSlot(int value)
return (value + 1) % capacity;
public IEnumerable<T> Latest()
slimLock.EnterReadLock();
return FetchItems().ToArray();
private IEnumerable<T> FetchItems()
IEnumerable<T> fetchedItems = Enumerable.Empty<T>();
fetchedItems = FetchItems(currentStart, upperBound);
return fetchedItems.Concat(FetchItems(0, currentIndex));
private IEnumerable<T> FetchItems(int start, int end)
for (int i = start; i <= end; i++)
public static void Main()
Console.WriteLine("Hello World");
var buffer = new CircularBuffer<float>(4);
Console.WriteLine(string.Format("Length should be 4: {0}", buffer.Latest().ToArray().Length ));