void RunWorker() { while (!shutdown) { lock (locker) { while (taskQueue.Count == 0 && !shutdown) { Monitor.Wait(locker); } } while (taskQueue.Count > 0) { bool shouldCancel = (shutdown && shutdownMode.Equals(ShutdownMode.CancelQueuedTasks)); if (shouldCancel) { break; } IWorkItem task = null; lock (locker) { if (taskQueue.Count > 0) { task = taskQueue.Dequeue(); } } if (task != null) { task.Execute(); } } } foreach (IWorkItem task in taskQueue) { task.Cancel("Shutdown"); } shutdownCompleted = true; }