using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace CompServ.Hub { internal class HubWorkerAssigner(ILogger logger, HubWorkerHolder holder) : BackgroundService { internal int _index = 0; internal int _assign = 0; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { logger.LogInformation("Start Assign service"); while (stoppingToken.IsCancellationRequested == false) { string urlToQueue = null; int ratio = default; var takeFail = false; lock (holder.Workers) { if (holder.Workers.Count == 0) { takeFail = true; } else { if (_index >= holder.Workers.Count) { _index = 0; _assign = 0; } var item = holder.Workers[_index]; urlToQueue = item.url; ratio = item.ratio; } } if (takeFail) { await Task.Delay(100, stoppingToken); continue; } logger.LogInformation($"Prep: {urlToQueue}"); await holder.Queue1.Writer.WriteAsync(urlToQueue, stoppingToken); //handle next worker with ratio _assign++; if (_assign >= ratio) { _index++; _assign = 0; lock (holder.Workers) { if (_index >= holder.Workers.Count) _index = 0; } } } } } }