1

Here's a simple implementation:

SemaphoreSlim s = new SemaphoreSlim(0, 1);              // No resource available.
Task<bool> w = s.WaitAsync(TimeSpan.FromSeconds(2));    // Timeout in 2 seconds.
s.Dispose();                                            // Dispose the semaphore earlier than timeout.
await w;                                                // Try await the task. Should it throw or should it hang?

I was expecting it to throw ObjectDisposedException, but it hang on me instead. Could anyone please explain me why?

Saar
  • 199
  • 1
  • 8
  • 1
    [From the docs](https://learn.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim.dispose?view=net-6.0) *"Unlike most of the members of SemaphoreSlim, Dispose is not thread-safe and may not be used concurrently with other members of this instance."* so you should make sure you are finished using it before disposing. Looking at the code, there is simply no mechanism to signal disposal to waiting threads. You should probably call `Release` before disposing, until it returns >0 – Charlieface Jan 21 '22 at 01:13

0 Answers0