Skip to content

Instantly share code, notes, and snippets.

@fakhrulhilal
Last active May 26, 2021 14:51
Show Gist options
  • Save fakhrulhilal/666b5ebd3d914e5930968b4279b6be0b to your computer and use it in GitHub Desktop.
Save fakhrulhilal/666b5ebd3d914e5930968b4279b6be0b to your computer and use it in GitHub Desktop.
Unit test for semaphore slim for throttling asynchronous tasks
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace UnitTests
{
[TestFixture]
class GivenSemaphoreSlim
{
const int threadToRun = 10;
const int maximumThread = 4;
[Test]
public async Task WhenWaitAsyncOutsideTaskRun()
{
int totalRunningThread = 0;
using (var semaphore = new SemaphoreSlim(maximumThread))
{
var throttleTasks = new List<Task>();
for (int i = 1; i <= threadToRun; i++)
{
await semaphore.WaitAsync();
throttleTasks.Add(Task.Run(async () =>
{
totalRunningThread++;
try
{
await SayHello(i, totalRunningThread);
Assert.That(totalRunningThread, Is.Not.GreaterThan(maximumThread));
}
finally
{
semaphore.Release();
totalRunningThread--;
}
}));
}
await Task.WhenAll(throttleTasks);
}
}
[Test]
public async Task WhenWaitAsyncInsideTaskRun()
{
int totalRunningThread = 0;
using (var semaphore = new SemaphoreSlim(maximumThread))
{
var throttleTasks = new List<Task>();
for (int i = 1; i <= threadToRun; i++)
{
throttleTasks.Add(Task.Run(async () =>
{
totalRunningThread++;
await semaphore.WaitAsync();
try
{
await SayHello(i, totalRunningThread);
Assert.That(totalRunningThread, Is.Not.GreaterThan(maximumThread));
}
finally
{
semaphore.Release();
totalRunningThread--;
}
}));
}
await Task.WhenAll(throttleTasks);
}
}
async Task SayHello(int sequence, int totalRunningThreads)
{
Say($"Say hello from thread-{sequence}, total running: {totalRunningThreads}");
await Task.Delay(TimeSpan.FromSeconds(2));
}
private void Say(string word) => TestContext.Out.WriteLine(word);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment