Search code examples
c#dynamicsemaphoreresize

Semaphore dynamic resizing C#


I'm trying to use semaphores to control how many instances of a job can be run at the same time. While this is fairly simple with a wait method, I also want the value to be configurable at runtime so that I can bump the count up or down.

I realize that there may be issues bumping the count down but is there a way to actually do this? Is this the right approach to be using semaphores?


Solution

  • While this is fairly simple with a wait method, I also want the value to be configurable at runtime so that I can bump the count up or down.

    I would not recommend using semaphores for this.

    If you're in .NET 4, my suggested method would be to create a custom TaskScheduler which would allow you to change the level of concurrency at runtime. You could then run your entire operation using a single Parallel.For/ForEach call passing this TaskScheduler in the options, and change the level of concurrency at runtime.

    This would make it fairly easy to handle moving levels up or down. When levels go up, you just add new threads as needed. When they go down, just remove that thread from your internal collection (but don't stop it), and let it finish its current work. This would allow you to scale as needed.