views:

49

answers:

2

What is the best way to reset a semaphore that have threads waiting on it. Right now all I can think of is just doing a while loop and releasing the semaphore until a semaphore full exception occurs. I'm not sure what is the best practice.

semaphore.Close();
semaphore = new Semaphore(0,1);

Or

while(true)
{
   try
   {
      semaphore.Release();
   }
   catch
   {
      break;
   }
}
semaphore = new Semaphore(0,1);
+3  A: 

If you want to do that, are you sure you want a Semaphore to start with? Perhaps a ManualResetEvent would be more appropriate?

Jon Skeet
+1  A: 

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 . . .

Jim Mischel