7

我需要编写一个循环算法来安排加载到 n 个端点吗?

所以如果我有服务器 A、B 和 C

我想确保为我收到的每个请求循环遍历它们。我如何在 C# 中做到这一点?

4

3 回答 3

22

仅作记录,循环的定义:

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);

链接到队列类:

http://msdn.microsoft.com/en-us/library/7977ey2c.aspx

于 2010-04-21T16:04:15.657 回答
7

与 ebpower 的想法相同,但关注的是下一项是什么,而不是下一项的索引是什么。

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];
    }
}
于 2013-06-03T18:58:04.480 回答
2

如果您的端点是通过列表或数组访问的,您只需要以循环方式递增索引:

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;
    }
}
于 2010-04-21T18:26:58.423 回答