轮询算法
static void Test9() { var strs = new List<string> { "192.168.100.125", "192.168.100.126", "192.168.100.127", "192.168.100.128", "192.168.100.130", "192.168.100.131" }; var addressEntry = new AddressEntry(strs); var item = addressEntry.GetAddress(); } protected class AddressEntry { #region Field private int _index; private int _lock; private readonly int _maxIndex; private readonly string[] _address; #endregion Field #region Constructor public AddressEntry(IEnumerable<string> address) { _address = address.ToArray(); _maxIndex = _address.Length - 1; } #endregion Constructor #region Public Method public string GetAddress() { while (true) { //如果无法得到锁则等待 if (Interlocked.Exchange(ref _lock, 1) != 0) { default(SpinWait).SpinOnce(); continue; } var address = _address[_index]; //设置为下一个 if (_maxIndex > _index) _index++; else _index = 0; //释放锁 Interlocked.Exchange(ref _lock, 0); return address; } } #endregion Public Method }