private void DownloadManagerThread() { Random random = new Random(); int round = 0; for (; ;) { Thread.Sleep(1000 * 3); if (this.State == ManagerState.Stop) { return; } BackgroundDownloadItem item = null; try { lock (this.ThisLock) { if (_settings.BackgroundDownloadItems.Count > 0) { { var items = _settings.BackgroundDownloadItems .Where(n => n.State == BackgroundDownloadState.Downloading) .Where(x => { if (x.Rank == 1) { return(0 == (!_cacheManager.Contains(x.Seed.Key) ? 1 : 0)); } else { return(0 == (x.Index.Groups.Sum(n => n.InformationLength) - x.Index.Groups.Sum(n => Math.Min(n.InformationLength, _existManager.GetCount(n))))); } }) .ToList(); item = items.FirstOrDefault(); } if (item == null) { var items = _settings.BackgroundDownloadItems .Where(n => n.State == BackgroundDownloadState.Downloading) .ToList(); if (items.Count > 0) { round = (round >= items.Count) ? 0 : round; item = items[round++]; } } } } } catch (Exception) { return; } if (item == null) { continue; } try { if (item.Rank == 1) { if (!_cacheManager.Contains(item.Seed.Key)) { item.State = BackgroundDownloadState.Downloading; _connectionsManager.Download(item.Seed.Key); } else { item.State = BackgroundDownloadState.Decoding; } } else { if (!item.Index.Groups.All(n => _existManager.GetCount(n) >= n.InformationLength)) { item.State = BackgroundDownloadState.Downloading; int limitCount = 256; foreach (var group in item.Index.Groups.ToArray().Randomize()) { if (_existManager.GetCount(group) >= group.InformationLength) { continue; } foreach (var key in _existManager.GetKeys(group, false)) { if (_connectionsManager.IsDownloadWaiting(key)) { limitCount--; if (limitCount <= 0) { goto End; } } } } List <Key> keyList = new List <Key>(); foreach (var group in item.Index.Groups.ToArray()) { if (_existManager.GetCount(group) >= group.InformationLength) { continue; } int downloadCount = 0; List <Key> tempKeys = new List <Key>(); foreach (var key in _existManager.GetKeys(group, false)) { if (_connectionsManager.IsDownloadWaiting(key)) { downloadCount++; } else { tempKeys.Add(key); } } int length = Math.Max(group.InformationLength, 32) - downloadCount; if (length <= 0) { continue; } random.Shuffle(tempKeys); foreach (var key in tempKeys.Take(length)) { _connectionsManager.Download(key); limitCount--; } if (limitCount <= 0) { goto End; } } End :; } else { item.State = BackgroundDownloadState.Decoding; } } } catch (Exception e) { item.State = BackgroundDownloadState.Error; Log.Error(e); this.Remove(item); } } }