Skip to content

Commit

Permalink
Verify throttle workload
Browse files Browse the repository at this point in the history
Add a unit test that verifies that Throttled does not allow work concurrent work that specified by the options.
  • Loading branch information
martincostello committed Jul 3, 2019
1 parent 5489923 commit ab8adf0
Showing 1 changed file with 48 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,54 @@ Task DoWork()
threadsSeen.Distinct().Count().ShouldBeGreaterThan(1);
}

[Fact]
public async Task Parallel_Processing_Does_Not_Exceed_Concurrency()
{
// Arrange
int maxConcurrency = 10;

var options = new ThrottledOptions()
{
MaxConcurrency = maxConcurrency,
Logger = _logger,
MessageMonitor = _monitor,
StartTimeout = Timeout.InfiniteTimeSpan,
ProcessMessagesSequentially = false,
};

var strategy = new Throttled(options);

long workDone = 0;
int loopCount = 1_000;
bool allWorkDone;

using (var semaphore = new SemaphoreSlim(maxConcurrency, maxConcurrency))
{
async Task DoWork()
{
if (!(await semaphore.WaitAsync(0)))
{
throw new InvalidOperationException("More workers are doing work than expected.");
}

Interlocked.Increment(ref workDone);
semaphore.Release();
}

// Act
for (int i = 0; i < loopCount; i++)
{
await strategy.StartWorkerAsync(DoWork, CancellationToken.None);
}

allWorkDone = SpinWait.SpinUntil(() => Interlocked.Read(ref workDone) >= 1000, TimeSpan.FromSeconds(10));
}

// Assert
allWorkDone.ShouldBeTrue();
workDone.ShouldBe(loopCount);
}

private static async Task AllowTasksToComplete(TaskCompletionSource<object> doneSignal)
{
doneSignal.SetResult(null);
Expand Down

0 comments on commit ab8adf0

Please sign in to comment.