我需要编写一个轮询算法来调度n个端点的负载?
如果我有A、B和C服务器
我想确保每次收到请求时都通过它们进行轮询。我如何在C#中实现这一点?
我需要编写一个轮询算法来调度n个端点的负载?
如果我有A、B和C服务器
我想确保每次收到请求时都通过它们进行轮询。我如何在C#中实现这一点?
仅供参考,轮询的定义:
http://en.wikipedia.org/wiki/Round-robin_scheduling
只需使用队列。从队列顶部取出一个元素,使用它并将其放回。这可以确保最近使用的元素始终是最后一个被选中的。
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);
队列类链接:
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];
}
}
Interlocked.Increment
will reach int.MaxValue
in very high load scenarios.
In that case, it handles the overflow condition and returns int.MinValue
as per documentation and this code will throw an System.ArgumentOutOfRangeException
while accessing the array because of the negative index.
A simple check can handle it:
... Interlocked.Increment(ref _position); if(_position == Int32.MinValue) { Interlocked.Exchange(ref _position, 0); } ...
- SalvatoreGarrubbapublic 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;
}
}