using Microsoft.Extensions.Hosting; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TEAMModelOS.SDK.DI { public class BackgroundWorkerQueue { private readonly ConcurrentQueue> _workItems = new(); private readonly SemaphoreSlim _signal = new(0); public async Task> DequeueAsync(CancellationToken cancellationToken) { await _signal.WaitAsync(cancellationToken); _workItems.TryDequeue(out var workItem); return workItem; } public void QueueBackgroundWorkItem(Func workItem) { ArgumentNullException.ThrowIfNull(workItem); _workItems.Enqueue(workItem); _signal.Release(); } } public class LongRunningService : BackgroundService { public LongRunningService(BackgroundWorkerQueue queue) { _queue = queue; } private readonly BackgroundWorkerQueue _queue; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var workItem = await _queue.DequeueAsync(stoppingToken); await workItem(stoppingToken); } } } }