Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,30 @@ public static async Task<IReadOnlyCollection<string>> AccessWithSemaphoreAsync(i
static async Task WorkerWithSemaphoreAsync(ProcessParams processParams)
{
_semaphore.WaitOne();
try
{
await Task.Delay(processParams.SleepDelay);

await Task.Delay(processParams.SleepDelay);

var output = string.Format("Semaphore: Thread {0} is accessing {1} at {2}",
processParams.SequenceNo,
nameof(_outputQueue),
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));

_outputQueue.Enqueue(output);
var output = string.Format("Semaphore: Thread {0} is accessing {1} at {2}",
processParams.SequenceNo,
nameof(_outputQueue),
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));

_semaphore.Release();
_outputQueue.Enqueue(output);
}
finally
{
_semaphore.Release();
}
}

public static void ReleaseMultipleTimes()
{
var semaphore = new Semaphore(initialCount: 2, maximumCount: 2);
using var semaphore = new Semaphore(initialCount: 2, maximumCount: 2);

semaphore.WaitOne();
semaphore.Release();

semaphore.Release();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace IntroductionToSemaphoreInCsharp;
public class ExampleWithSemaphoreSlim
{
private static readonly ConcurrentQueue<string> _outputQueue = new();
private static readonly SemaphoreSlim _semaphoreSlim = new(3, 3);
private static readonly SemaphoreSlim _semaphoreSlim = new(initialCount: 3, maxCount: 3);

public static async Task<IReadOnlyCollection<string>> AccessWithSemaphoreSlimAsync(int sleepDelay)
{
Expand All @@ -26,19 +26,21 @@ public static async Task<IReadOnlyCollection<string>> AccessWithSemaphoreSlimAsy

static async Task WorkerWithSemaphoreSlimAsync(ProcessParams processParams)
{
if (processParams is null)
return;

await _semaphoreSlim.WaitAsync();
try
{
await Task.Delay(processParams.SleepDelay);

await Task.Delay(processParams.SleepDelay);

var output = string.Format("SemaphoreSlim: Thread {0} is accessing {1} at {2}",
processParams.SequenceNo,
nameof(_outputQueue),
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
_outputQueue.Enqueue(output);
var output = string.Format("SemaphoreSlim: Thread {0} is accessing {1} at {2}",
processParams.SequenceNo,
nameof(_outputQueue),
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));

_semaphoreSlim.Release();
_outputQueue.Enqueue(output);
}
finally
{
_semaphoreSlim.Release();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
using IntroductionToSemaphoreInCsharp;
using System.Diagnostics;

const int SleepDelay = 50;

Console.WriteLine("Executing with Semaphore...");
var outputQueue = await ExampleWithSemaphore.AccessWithSemaphoreAsync(SleepDelay);
foreach(var output in outputQueue)
var stopwatch = Stopwatch.StartNew();
var semaphoreTask = ExampleWithSemaphore.AccessWithSemaphoreAsync(SleepDelay);
var semaphoreBlockedMs = stopwatch.ElapsedMilliseconds;
var outputQueue = await semaphoreTask;
foreach (var output in outputQueue)
{
Console.WriteLine(output);
}

Console.WriteLine("Executing with SemaphoreSlim...");
outputQueue = await ExampleWithSemaphoreSlim.AccessWithSemaphoreSlimAsync(SleepDelay);
stopwatch.Restart();
var semaphoreSlimTask = ExampleWithSemaphoreSlim.AccessWithSemaphoreSlimAsync(SleepDelay);
var semaphoreSlimBlockedMs = stopwatch.ElapsedMilliseconds;
outputQueue = await semaphoreSlimTask;
foreach (var output in outputQueue)
{
Console.WriteLine(output);
}

Console.WriteLine($"Semaphore kept the caller busy for {semaphoreBlockedMs} ms");
Console.WriteLine($"SemaphoreSlim kept the caller busy for {semaphoreSlimBlockedMs} ms");

Console.WriteLine("Calling Release multiple times...");
ExampleWithSemaphore.ReleaseMultipleTimes();
try
{
ExampleWithSemaphore.ReleaseMultipleTimes();
}
catch (SemaphoreFullException ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -10,10 +10,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
<PackageReference Include="coverlet.collector" Version="10.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="MSTest.TestAdapter" Version="4.5.3" />
<PackageReference Include="MSTest.TestFramework" Version="4.5.3" />
</ItemGroup>

<ItemGroup>
Expand Down
36 changes: 28 additions & 8 deletions threads-csharp/IntroductionToSemaphoreInCsharp/Tests/UnitTests.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,52 @@
using IntroductionToSemaphoreInCsharp;
using System.Diagnostics;

namespace Tests;

[TestClass]
public class UnitTests
{
const int SleepDelay = 50;
const int SleepDelay = 200;

[TestMethod]
public async Task GivenSomeConcurrentCode_WhenAccessWithSemaphoreAsyncIsInvoked_ThenAllThreadsShouldExecute()
public async Task GivenSomeConcurrentCode_WhenAccessWithSemaphoreAsyncIsInvoked_ThenAllThreadsExecuteAndTheCallerIsBlocked()
{
var output = await ExampleWithSemaphore.AccessWithSemaphoreAsync(SleepDelay);
var stopwatch = Stopwatch.StartNew();
var task = ExampleWithSemaphore.AccessWithSemaphoreAsync(SleepDelay);
var callerBlockedMs = stopwatch.ElapsedMilliseconds;
var output = await task;

Assert.AreEqual(Constants.NumberOfThreads, output.Count);
Assert.IsGreaterThanOrEqualTo(SleepDelay, callerBlockedMs);
}

[TestMethod]
public async Task GivenSomeConcurrentCode_WhenAccessWithSemaphoreSlimAsyncIsInvoked_ThenAllThreadsShouldExecute()
public async Task GivenSomeConcurrentCode_WhenAccessWithSemaphoreSlimAsyncIsInvoked_ThenAllThreadsExecuteAndTheCallerIsNotBlocked()
{
var output = await ExampleWithSemaphoreSlim.AccessWithSemaphoreSlimAsync(SleepDelay);
var stopwatch = Stopwatch.StartNew();
var task = ExampleWithSemaphoreSlim.AccessWithSemaphoreSlimAsync(SleepDelay);
var callerBlockedMs = stopwatch.ElapsedMilliseconds;
var output = await task;

Assert.AreEqual(Constants.NumberOfThreads, output.Count);
Assert.IsLessThan(SleepDelay, callerBlockedMs);
}

[TestMethod]
[ExpectedException(typeof(SemaphoreFullException))]
public void GivenASemaphore_WhenReleaseMultipleTimesIsInvoked_ThenAnExceptionIsThrown()
{
ExampleWithSemaphore.ReleaseMultipleTimes();
Assert.ThrowsExactly<SemaphoreFullException>(ExampleWithSemaphore.ReleaseMultipleTimes);
}
}

[TestMethod]
public void GivenASemaphoreSlimWithoutMaxCount_WhenReleasedOnceTooOften_ThenTheCountGrowsWithoutAnException()
{
using var semaphoreSlim = new SemaphoreSlim(1);

semaphoreSlim.Wait();
semaphoreSlim.Release();
semaphoreSlim.Release();

Assert.AreEqual(2, semaphoreSlim.CurrentCount);
}
}
Loading