I want to assign a list of objects in a SemaphoreSlim fashion, e.g. suppose each object can be used by two threads at the same time. My plan is to create a SemaphoreSlim class for each object in this list, but then my question is how should I check whether a SemaphoreSlim can be used right now?
I don't want to call Wait() since if an object is not available I can move on to the next one in the list. I don't want to check CurrentCount property either since I don't think it will be thread safe if multiple threads checked the CurrentCount at the same time and the decided to call Wait() if CurrentCount is larger than zero.
So what is the ideal solution for this scenario?
BTW - I can use other solutions - not just SemaphoreSlim.
I suspect you can use Wait(TimeSpan.Zero)
to say "try to acquire the semaphore, but abandon the attempt if you can't do so immediately."
That would be my expectation, but the documentation doesn't explicitly talk about what happens if you pass in TimeSpan.Zero
. It's worth at least investigating that option further, IMO.
See more on this question at Stackoverflow