Reputation: 2396
I need to write a round robin algorithm to schedule load to n endpoints?
So if I have servers A, B and C
I wanted to make sure to round-robin through them for each request I get. How do I do this in C#?
Upvotes: 8
Views: 20781
Reputation: 4183
Same idea as ebpower, but focussing on what is the next item rather than what is the index of the next item.
public class RoundRobinList<T>
{
private readonly IList<T> _list;
private readonly int _size;
private int _position;
public RoundRobinList(IList<T> list)
{
if (!list.Any())
throw new NullReferenceException("list");
_list = new List<T>(list);
_size = _list.Count;
}
public T Next()
{
if (_size == 1)
return _list[0];
Interlocked.Increment(ref _position);
var mod = _position % _size;
return _list[mod];
}
}
Upvotes: 8
Reputation: 8531
If your endpoints are accessed through a List or Array, you only need to increment an index in a circular fashion:
public class RoundRobinIndex
{
volatile int index = 0;
int count;
public int Next
{
get
{
if (index == count)
{
index = 0;
}
return index++;
}
}
public RoundRobinIndex(int countArg)
{
count = countArg;
}
}
Upvotes: 2
Reputation: 115538
Just for the record, definition of round robin:
http://en.wikipedia.org/wiki/Round-robin_scheduling
Just use a queue. Take one off of the top, use it and put it back. This ensures that the most recent one used will always be the last one to be picked up.
Queue<Server> q = new Queue<Server>();
//get the next one up
Server s = q.DeQueue();
//Use s;
//put s back for later use.
q.Enqueue(s);
Link to the queue class:
http://msdn.microsoft.com/en-us/library/7977ey2c.aspx
Upvotes: 23