public static void ProcessQueuedCallbacks() { while (true) { _managementEvent.WaitOne(); while (_queuedCallbacks.TryDequeue(out var callback)) { if (_idleThreads.TryTake(out ThreadState threadState)) { threadState.Run(callback); } else { var threads = Interlocked.Increment(ref _threads); if (threads <= MaxThreads) { threadState = new ThreadState(); threadState.Run(callback); } else { Interlocked.Decrement(ref _threads); // TODO: Restore to front of queue instead of back (for fairness) _queuedCallbacks.Enqueue(callback); // Wait for next event signal break; } } } } }