Round Robin is a very simple but in the same time very useful algorithm,
but there is no native implementation in C# . So here is a simple but powerful and thread-safe implementation of the Round Robin algorithm in C#.
Usage
//installation
dotnet add package RoundRobin
Install-Package RoundRobin
var roundRobinList = new RoundRobinList<int>(
new List<int>{
1,2,3,4,5
}
);
for (var i = 0; i < 8; i++)
{
Write($"{roundRobinList.Next()},");
}
//result
//1,2,3,4,5,1,2,3,
Also you can increase/decrease the weights, by doing so you will be able to increase/decrease the priority of an element in the Round Robin list
var roundRobinList = new RoundRobinList<int>(
new List<int>{
1,2,3,4,5
}
);
//the weight of the element 1 will be increase by 2 units
roundRobinList.IncreaseWeight(element:1, amount:2);
for (var i = 0; i < 10; i++)
{
Write($"{roundRobinList.Next()},");
}
//result
//1,1,1,2,3,4,5,1,1,1
Enjoy coding :)
I like this implementation of round robin, it just does one thing and that's round robin (I've seen implementations of RR where assumption is always load balancing and http is baked right in :D )
I do however suggest a few features:
The second one would be good when let's say I have 5 endpoints and I've 5 clients with weight of 10 each (and maybe one of the machine is more reliable and has more resources, so maybe I want to set weight of 15)
Now when my app is running, if a machine goes down or fails somehow, I'd like to decrement the weight by 1, and if a machine goes down for a long time, it'd be taken off of our round robin, but before it reaches 0 and it comes back online, then we could reset it back to original value.
Basically requirement would be weighted round robin with the ability to change the weight of current instance.