There is no other way to ensure that an existing semaphore is full, other than doing the loop that you show. If you really want to do that, then your method is the way. However, you probably should change your catch
to catch (SemaphoreFullException)
.
That said, there are particular dangers to doing what you're talking about. If some other thread has acquired the semaphore before you start filling it, or does a WaitOne
on the semaphore while you're trying to fill it, then when that thread does a Release
, it's going to get a SemaphoreFullException
.
If you're "resetting" your program in preparation for starting a new run or something, then your first example is the way to go: destroy the semaphore and create a new one. Of course, before you do that you'll want to make sure that there aren't any active threads that will want to use the old semaphore . . .