namespace ThreadPilot.Services { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Models; public class VirtualizedProcessService : IVirtualizedProcessService, IDisposable { private readonly IProcessService processService; private readonly ILogger logger; private readonly SemaphoreSlim loadingSemaphore = new(1, 1); private readonly ConcurrentDictionary batchCache = new(); private readonly System.Threading.Timer backgroundPreloadTimer; private List? allProcesses; private DateTime lastFullRefresh = DateTime.MinValue; private bool disposed; public VirtualizedProcessConfig Configuration { get; set; } = new(); public event EventHandler? BatchLoadProgress; public event EventHandler? BackgroundBatchLoaded; public VirtualizedProcessService( IProcessService processService, ILogger logger) { this.processService = processService ?? throw new ArgumentNullException(nameof(processService)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); // Set up background preloading timer this.backgroundPreloadTimer = new System.Threading.Timer(this.BackgroundPreloadCallback, null, Timeout.Infinite, Timeout.Infinite); } public async Task InitializeAsync() { this.logger.LogDebug("Initializing VirtualizedProcessService with batch size: {BatchSize}", this.Configuration.BatchSize); // Perform initial load to get total count await this.RefreshAllProcessesAsync(false); } public async Task GetTotalProcessCountAsync(bool activeApplicationsOnly = false) { await this.EnsureProcessesLoadedAsync(activeApplicationsOnly); if (activeApplicationsOnly) { return this.allProcesses?.Count(p => p.HasVisibleWindow) ?? 0; } return this.allProcesses?.Count ?? 0; } public async Task LoadProcessBatchAsync(int batchIndex, bool activeApplicationsOnly = false) { var cacheKey = $"batch_{batchIndex}_{activeApplicationsOnly}"; if (this.batchCache.TryGetValue(cacheKey.GetHashCode(), out var cachedBatch)) { this.logger.LogDebug("Returning cached batch {BatchIndex}", batchIndex); return cachedBatch; } var stopwatch = Stopwatch.StartNew(); await this.EnsureProcessesLoadedAsync(activeApplicationsOnly); var filteredProcesses = activeApplicationsOnly ? this.allProcesses?.Where(p => p.HasVisibleWindow).ToList() ?? new List() : this.allProcesses ?? new List(); var totalCount = filteredProcesses.Count; var totalBatches = (int)Math.Ceiling((double)totalCount / this.Configuration.BatchSize); var startIndex = batchIndex * this.Configuration.BatchSize; var batchProcesses = filteredProcesses .Skip(startIndex) .Take(this.Configuration.BatchSize) .ToList(); var result = new ProcessBatchResult { Processes = batchProcesses, BatchIndex = batchIndex, TotalBatches = totalBatches, TotalProcessCount = totalCount, HasMoreBatches = batchIndex < totalBatches - 1, LoadTime = stopwatch.Elapsed, }; // Cache the result this.batchCache.TryAdd(cacheKey.GetHashCode(), result); this.logger.LogDebug( "Loaded batch {BatchIndex}/{TotalBatches} with {ProcessCount} processes in {LoadTime}ms", batchIndex, totalBatches, batchProcesses.Count, stopwatch.ElapsedMilliseconds); return result; } public async Task> LoadProcessBatchesAsync(int startBatchIndex, int batchCount, bool activeApplicationsOnly = false) { var results = new List(); var totalBatches = await this.GetTotalBatchCountAsync(activeApplicationsOnly); for (int i = 0; i < batchCount && (startBatchIndex + i) < totalBatches; i++) { var batchIndex = startBatchIndex + i; var batch = await this.LoadProcessBatchAsync(batchIndex, activeApplicationsOnly); results.Add(batch); // Report progress this.BatchLoadProgress?.Invoke(this, new BatchLoadProgressEventArgs { LoadedBatches = i + 1, TotalBatches = batchCount, LoadedProcesses = results.Sum(r => r.Processes.Count), TotalProcesses = batch.TotalProcessCount, StatusMessage = $"Loaded batch {batchIndex + 1} of {totalBatches}", }); } return results; } public async Task PreloadNextBatchAsync(int currentBatchIndex, bool activeApplicationsOnly = false) { if (!this.Configuration.EnableBackgroundLoading) { return; } var nextBatchIndex = currentBatchIndex + 1; var totalBatches = await this.GetTotalBatchCountAsync(activeApplicationsOnly); if (nextBatchIndex < totalBatches) { _ = Task.Run(async () => { try { if (!this.Configuration.EnableBackgroundLoading) { return; } var batch = await this.LoadProcessBatchAsync(nextBatchIndex, activeApplicationsOnly); this.BackgroundBatchLoaded?.Invoke(this, batch); } catch (Exception ex) { this.logger.LogDebug(ex, "Failed to preload batch {BatchIndex}", nextBatchIndex); } }); } } public async Task> SearchProcessesAsync(string searchTerm, bool activeApplicationsOnly = false) { if (string.IsNullOrWhiteSpace(searchTerm)) { return new List(); } await this.EnsureProcessesLoadedAsync(activeApplicationsOnly); var filteredProcesses = activeApplicationsOnly ? this.allProcesses?.Where(p => p.HasVisibleWindow) ?? Enumerable.Empty() : this.allProcesses ?? Enumerable.Empty(); return filteredProcesses .Where(p => p.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) || (p.MainWindowTitle?.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ?? false)) .ToList(); } public async Task RefreshBatchAsync(int batchIndex, bool activeApplicationsOnly = false) { var cacheKey = $"batch_{batchIndex}_{activeApplicationsOnly}"; this.batchCache.TryRemove(cacheKey.GetHashCode(), out _); // Force refresh of all processes await this.RefreshAllProcessesAsync(activeApplicationsOnly); return await this.LoadProcessBatchAsync(batchIndex, activeApplicationsOnly); } public void ClearCache() { this.batchCache.Clear(); this.allProcesses = null; this.lastFullRefresh = DateTime.MinValue; this.logger.LogInformation("Cleared virtualized process cache"); } private async Task EnsureProcessesLoadedAsync(bool activeApplicationsOnly) { if (this.allProcesses == null || DateTime.UtcNow - this.lastFullRefresh > this.Configuration.RefreshInterval) { await this.RefreshAllProcessesAsync(activeApplicationsOnly); } } private async Task RefreshAllProcessesAsync(bool activeApplicationsOnly) { await this.loadingSemaphore.WaitAsync(); try { this.logger.LogDebug("Refreshing all processes (activeOnly: {ActiveOnly})", activeApplicationsOnly); var processes = activeApplicationsOnly ? await this.processService.GetActiveApplicationsAsync() : await this.processService.GetProcessesAsync(); this.allProcesses = processes.ToList(); this.lastFullRefresh = DateTime.UtcNow; // Clear batch cache since underlying data changed this.batchCache.Clear(); this.logger.LogDebug("Refreshed {ProcessCount} processes", this.allProcesses.Count); } finally { this.loadingSemaphore.Release(); } } private async Task GetTotalBatchCountAsync(bool activeApplicationsOnly) { var totalCount = await this.GetTotalProcessCountAsync(activeApplicationsOnly); return (int)Math.Ceiling((double)totalCount / this.Configuration.BatchSize); } private void BackgroundPreloadCallback(object? state) { TaskSafety.FireAndForget(this.BackgroundPreloadCallbackAsync(), ex => { this.logger.LogDebug(ex, "Background process refresh failed"); }); } private async Task BackgroundPreloadCallbackAsync() { try { if (!this.Configuration.EnableBackgroundLoading) { return; } // Refresh processes in background await this.RefreshAllProcessesAsync(false); } catch (Exception ex) { this.logger.LogDebug(ex, "Background process refresh failed"); } } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { this.backgroundPreloadTimer?.Dispose(); this.loadingSemaphore?.Dispose(); this.batchCache.Clear(); this.logger.LogInformation("VirtualizedProcessService disposed"); } this.disposed = true; } } public void Dispose() { this.Dispose(disposing: true); GC.SuppressFinalize(this); } } }