如何检查是否可以输入一个SemaphoreSlim?

How to check whether a SemaphoreSlim can be entered?

我想以 SemaphoreSlim 方式分配一个对象列表,例如假设每个对象可以同时被两个线程使用。我的计划是为这个列表中的每个对象创建一个 SemaphoreSlim class,但我的问题是我应该如何检查现在是否可以使用 SemaphoreSlim?

我不想调用 Wait(),因为如果某个对象不可用,我可以转到列表中的下一个对象。我也不想检查 CurrentCount 属性,因为我认为如果多个线程同时检查 CurrentCount 并且如果 CurrentCount 大于零则决定调用 Wait() 将不是线程安全的。

那么这个场景的理想解决方案是什么?

顺便说一句 - 我可以使用其他解决方案 - 不仅仅是 SemaphoreSlim。

怀疑你可以用Wait(TimeSpan.Zero)说"try to acquire the semaphore, but abandon the attempt if you can't do so immediately."

这是我的期望,但文档没有明确说明如果传入 TimeSpan.Zero 会发生什么。 IMO,至少值得进一步研究该选项。

MSDN中明确提及。

If the timeout is set to zero milliseconds, the method doesn't block. It tests the state of the wait handle and returns immediately.