using System.Collections.Concurrent; using Models.Handler; using Models.Model.Backend; namespace Backend.Handler; public class ThreadHandler { private readonly DbHandler _dbHandler; private readonly Communication _communication; private readonly IpScanner _ipScanner; private readonly ContentFilter _contentFilter; private bool _communicationStopped; private bool _ipScannerStopped; private bool _contentFilterStopped; private bool _stopSignal; public ThreadHandler() { ConcurrentQueue contentQueue = new(); ConcurrentQueue discardedQueue = new(); _dbHandler = new(contentQueue, discardedQueue); _communication = new(_dbHandler, this); _ipScanner = new(contentQueue, _dbHandler, discardedQueue); _contentFilter = new(contentQueue, _dbHandler); } public void Start() { //Thread scanner = new(StartScanner); //Thread indexer = new(StartIndexer); Thread database = new(StartDbHandler); Thread discarded = new(StartDiscardedDbHandler); Thread communication = new(StartCommunicationHandler); //scanner.Start(); //indexer.Start(); database.Start(); discarded.Start(); communication.Start(); //scanner.Join(); //indexer.Join(); database.Join(); discarded.Join(); communication.Join(); } public static void ManualGc() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } private void StartScanner() { Thread.Sleep(10000); // Let the database handler instantiate and warm up first. WaitHandle[] wait = _ipScanner.Start(4); WaitHandle.WaitAll(wait); Console.WriteLine("Scanner finished"); _ipScannerStopped = true; } private void StartIndexer() { while (!_stopSignal) { WaitHandle[] wait = _contentFilter.Start(); WaitHandle.WaitAll(wait); Thread.Sleep(300000); // 5 minutes } Console.WriteLine("Indexer finished"); _contentFilterStopped = true; } private void StartDbHandler() { _dbHandler.StartContent(); } private void StartDiscardedDbHandler() { WaitHandle[] wait = _dbHandler.Start(2); WaitHandle.WaitAll(wait); Console.WriteLine("Discarded DbHandler finished"); } private void StartCommunicationHandler() { WaitHandle[] wait = _communication.Start(); WaitHandle.WaitAll(wait); Console.WriteLine("Communicator finished"); _communicationStopped = true; } private void StopCommunicator() { Thread t = new(_communication.Stop); t.Start(); t.Join(); } public void Stop() { _stopSignal = true; _ipScanner.Stop(); _contentFilter.Stop(); StopCommunicator(); bool stopping = true; while (stopping) { if (_communicationStopped && _ipScannerStopped && _contentFilterStopped) { _dbHandler.Stop(); stopping = false; } Thread.Sleep(3000); } } }