public void StartTask() { bool finished = false; while (!finished) { while (NumberOfOutstandingTasks >= SimultaneiousTasksLimit) { System.Threading.Thread.Sleep(100); } lock (lockObject) { if (NumberOfOutstandingTasks >= SimultaneiousTasksLimit) { // Another thread added a task to the queue before we could get the lock. continue; } RemvoeExpiredTasks(); if (CurrentTasks.Count == WindowLimit) { TimeSpan waitTime = CurrentTasks.Dequeue() - DateTime.Now; if (waitTime.TotalMilliseconds > 0) { Throttled?.Invoke(this, new ThottledEventArgs(waitTime)); System.Threading.Thread.Sleep(waitTime); } } System.Threading.Interlocked.Increment(ref _numberOfOutstandingTasks); CurrentTasks.Enqueue(DateTime.Now + WindowSize); finished = true; } } }
public void AddTask(Task task) { CurrentTasks.Enqueue(task); ProcessTasks(); }