From 834e938bde06873516645a9bb022391f9c24ce00 Mon Sep 17 00:00:00 2001 From: Vladimir Pecanac Date: Fri, 13 Nov 2026 13:13:07 +0100 Subject: [PATCH] Update Semaphore sample to .NET 11, release in finally, time the caller Both projects target net11.0. MSTest 4.5.3, Microsoft.NET.Test.Sdk 18.12.0 and coverlet.collector 10.1.0. Both workers release the semaphore in a finally block, the SemaphoreSlim null check is removed, ReleaseMultipleTimes disposes its Semaphore, Program.cs times how long each call keeps the caller busy and prints the SemaphoreFullException. Tests use Assert.ThrowsExactly, assert the caller-busy bounds and cover over-release on a SemaphoreSlim without maxCount. --- .../ExampleWithSemaphore.cs | 26 ++++++++------ .../ExampleWithSemaphoreSlim.cs | 28 ++++++++------- .../IntroductionToSemaphoreInCsharp.csproj | 2 +- .../Program.cs | 25 ++++++++++--- .../Tests/Tests.csproj | 10 +++--- .../Tests/UnitTests.cs | 36 ++++++++++++++----- 6 files changed, 85 insertions(+), 42 deletions(-) diff --git a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphore.cs b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphore.cs index 708bc41695..9fc645180c 100644 --- a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphore.cs +++ b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphore.cs @@ -27,26 +27,30 @@ public static async Task> 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(); } -} \ No newline at end of file +} diff --git a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphoreSlim.cs b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphoreSlim.cs index 7b309e53ce..2ce19c3e81 100644 --- a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphoreSlim.cs +++ b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/ExampleWithSemaphoreSlim.cs @@ -7,7 +7,7 @@ namespace IntroductionToSemaphoreInCsharp; public class ExampleWithSemaphoreSlim { private static readonly ConcurrentQueue _outputQueue = new(); - private static readonly SemaphoreSlim _semaphoreSlim = new(3, 3); + private static readonly SemaphoreSlim _semaphoreSlim = new(initialCount: 3, maxCount: 3); public static async Task> AccessWithSemaphoreSlimAsync(int sleepDelay) { @@ -26,19 +26,21 @@ public static async Task> 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(); + } } -} \ No newline at end of file +} diff --git a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp.csproj b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp.csproj index 2150e3797b..9c8a72d56d 100644 --- a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp.csproj +++ b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net11.0 enable enable diff --git a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/Program.cs b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/Program.cs index 80efe9e8b4..9b6739e71c 100644 --- a/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/Program.cs +++ b/threads-csharp/IntroductionToSemaphoreInCsharp/IntroductionToSemaphoreInCsharp/Program.cs @@ -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(); \ No newline at end of file +try +{ + ExampleWithSemaphore.ReleaseMultipleTimes(); +} +catch (SemaphoreFullException ex) +{ + Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); +} diff --git a/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/Tests.csproj b/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/Tests.csproj index ac3ba24927..8bd0eff738 100644 --- a/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/Tests.csproj +++ b/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/Tests.csproj @@ -1,7 +1,7 @@ - net8.0 + net11.0 enable enable @@ -10,10 +10,10 @@ - - - - + + + + diff --git a/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/UnitTests.cs b/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/UnitTests.cs index f439505280..e84bf4a449 100644 --- a/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/UnitTests.cs +++ b/threads-csharp/IntroductionToSemaphoreInCsharp/Tests/UnitTests.cs @@ -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(ExampleWithSemaphore.ReleaseMultipleTimes); } -} \ No newline at end of file + + [TestMethod] + public void GivenASemaphoreSlimWithoutMaxCount_WhenReleasedOnceTooOften_ThenTheCountGrowsWithoutAnException() + { + using var semaphoreSlim = new SemaphoreSlim(1); + + semaphoreSlim.Wait(); + semaphoreSlim.Release(); + semaphoreSlim.Release(); + + Assert.AreEqual(2, semaphoreSlim.CurrentCount); + } +}