Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SemaphoreSlim usage limitations

Tags:

c#

.net

.net-core

Documentation says:

The SemaphoreSlim class represents a lightweight, fast semaphore that can be used for waiting within a single process when wait times are expected to be very short.

What does very short mean? Does anybody know explicit time value in milliseconds? Is it possible to use a SemaphoreSlim instance, if wait time will be about 5 minutes?

like image 666
Alexander Avatar asked Sep 14 '25 13:09

Alexander


1 Answers

Is it possible to use a SemaphoreSlim instance, if wait time will be about 5 minutes?

Yes, that's fine.

The documentation should not be read to mean that SemaphoreSlim is to be used only when wait times are expected to be very short. Rather that it's more suitable for such situations than the heavier-weight alternative Semaphore.

What constitutes "very short"? Hard to say, since it's dependent on what else is going on in the code. But I'd put it in the tens of milliseconds range, possibly as long as hundreds of milliseconds. Once you're talking about seconds or longer, I would expect there to be no significant advantage of the one over the other.

If your wait times are significantly longer, then the overheads of allocating and managing the Semaphore class as compared to the SemaphoreSlim class are likely not to be significant in the overall profile of your executing code. So you can easily get away with using Semaphore in such situations without significantly impacting the performance of your code, even though it's technically less efficient.

Personally, I use SemaphoreSlim instead of Semaphore always, except where I need a feature of the latter that the former doesn't support. That doesn't come up very often, and even less now with the even-higher abstractions available in C# and .NET for coordinating concurrently running code. Even using a semaphore at all has become somewhat of a rarity for me.

like image 138
Peter Duniho Avatar answered Sep 16 '25 03:09

Peter Duniho