Increase / Decrease the number of available slots in SemaphoreSlim

EDIT : My question, as originally formulated, implies that SemaphoreSlim creates and destroys threads that are not accurate. Repeating to use “slots” instead of “streams”, I think this is more accurate.

I use the class SemaphoreSlimto control the speed at which I access this resource, and it works great. However, I am afraid how I can dynamically increase and decrease the number of slots available.

Ideally, SemaphoreSlim will have methods Increase()and Decrease()with the following characteristics:

  • Increase() increases the maximum number of slots available by 1
  • Decrease() reduces the maximum number of slots available by 1
  • These methods do not wait; they return immediately.
  • When the maximum number of slots is configured, subsequent calls are Increase()equivalent to noop (no exception selected)
  • When the minimum number of slots is configured, subsequent calls are Decrease()equivalent to noop (no exception is thrown)
  • When Decrease()called and all slots are used, the maximum number of slots decreases when the slots are released.

Is there a .NET constructor that allows something like this?

+4
source share
2 answers

( ):

public static void Increase(this SemaphoreSlim semaphore)
{
  try
  {
    semaphore.Release();
  }
  catch
  {
    // An exception is thrown if we attempt to exceed the max number of concurrent tasks
    // It safe to ignore this exception
  }
}

:

var semaphore = new SemaphoreSlim(2, 5);  // two slot are initially available and the max is 5 slots
semaphore.Increase();  // three slots are now available
semaphore.Increase();  // four slots are now available
semaphore.Increase();  // five slots are now available
semaphore.Increase();  // we are attempting to exceed the max; an exception is thrown but it caught and ignored. The number of available slots remains five

, "()". ?

0

All Articles