Skip to content

Commit

Permalink
Merge pull request #26477 from sharwell/handle-empty-queue
Browse files Browse the repository at this point in the history
Handle empty queue in WaitForPendingWorkAsync
  • Loading branch information
sharwell authored May 1, 2018
2 parents eb458d9 + 4392067 commit a550ee1
Showing 1 changed file with 18 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -196,26 +196,29 @@ private void NotifyOnForegroundWorker()

private async Task WaitForPendingWorkAsync()
{
await _workQueue.WaitForItemsAsync().ConfigureAwait(false);
while (true)
{
var current = Environment.TickCount;
var nextItem = _workQueue.PeekNextItemTime();
await _workQueue.WaitForItemsAsync().ConfigureAwait(false);
if (!_workQueue.TryPeekNextItemTime(out var nextItem))
{
// Need to go back and wait for an item
continue;
}

// The next item is ready to run
if (nextItem - current <= 0)
if (nextItem - Environment.TickCount <= 0)
{
break;
}

// wait some and re-check since there could be another one inserted before the first one while we were waiting.
await Task.Delay(MinimumDelayBetweenProcessing).ConfigureAwait(continueOnCapturedContext: false);
await Task.Delay(MinimumDelayBetweenProcessing).ConfigureAwait(false);
}

// Throttle how often we run by waiting MinimumDelayBetweenProcessing since the last time we processed notifications
if (Environment.TickCount - _lastProcessedTimeInMS < MinimumDelayBetweenProcessing)
{
await Task.Delay(MinimumDelayBetweenProcessing).ConfigureAwait(continueOnCapturedContext: false);
await Task.Delay(MinimumDelayBetweenProcessing).ConfigureAwait(false);
}
}

Expand Down Expand Up @@ -344,12 +347,18 @@ private void Enqueue_NoLock(LinkedListNode<PendingWork> entry)
return;
}

public int PeekNextItemTime()
public bool TryPeekNextItemTime(out int minimumRunPoint)
{
lock (_gate)
{
Contract.Requires(_list.Count > 0);
return _list.First.Value.MinimumRunPointInMS;
if (_list.Count == 0)
{
minimumRunPoint = 0;
return false;
}

minimumRunPoint = _list.First.Value.MinimumRunPointInMS;
return true;
}
}

Expand Down

0 comments on commit a550ee1

Please sign in to comment.