private void MainExecutionThread() { while (true) { if (disposed) { return; } while (workerThreads.Count < maxThreadCount) { workerThreads.Add(new WorkerThread(checkQueuedWorkItems)); } while (workerThreads.Count > maxThreadCount) { WorkerThread availableThread = workerThreads.FirstOrDefault(x => x.IsAvailable); if (availableThread == null) { break; } workerThreads.Remove(availableThread); availableThread.Dispose(); } lock (workItems) { while (workItems.Count > 0) { if (disposed) { return; } WorkerThread availableThread = workerThreads.FirstOrDefault(x => x.IsAvailable); if (availableThread == null) { break; } var workItem = workItems.Dequeue(); availableThread.ExecuteWorkItem(workItem); } } if (disposed) { return; } checkQueuedWorkItems.WaitOne(); if (disposed) { return; } } }