Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reduce the Semaphore Count

Status
Not open for further replies.

PGO01

Programmer
Jan 8, 2008
156
GB
I'm trying to create a sample application that uses a semaphore to restrict the number of instances allowed to be open on a given machine at any 1 time.

I have got it working as far as it shows a message if the semaphore is full, and closes - but the problem I am having is the semaphore count is not reducing when I close down 1 or more of the instances.

For example if I set the number of allowed instances to 3, and open 1 - fine, 2 - fine, 3 - fine, 4 - I get a message and the 4th instance closes, fine. I close the 3rd instance, I close the 2nd instance (so now 1 is left open), try to open another and I get the message again saying that the semaphore is full.

I want to be able to open 3 instances, close 2, and open 2 again, etc, so that it only shows the message if the limit I've imposed is exceeded.

In my OnClosed event handler I've done
Code:
if (semaphore != null) semaphore.Close();

And that is what I thought would reduce the count on the semaphore. What am I missing - can't see it in any examples on MSDN. Any ideas?

Many thanks,
 
>if (semaphore != null) semaphore.Close();
[tt]if (semaphore != null) semaphore.[red]Release()[/red]);[/tt]

>And that is what I thought would reduce the count on the semaphore.
The normative thinking is "increase" to the limit made available by its constructor rather than "reduce" the number to zero.
 
Code:
if (semaphore != null) semaphore.Release();
This causes an error because the semaphore is already at it's maximum number of releases.

"Adding the given count to the semaphore would cause it to exceed its maximum count.
 
Then I don't understand. When applying the Close() method, the semaphore would not be released for the next WaitOne() to process and effectively reduce the max count by 1. Take for instance the demo in the documentation:
if instead of applying Release(), you use Close(), the application would hang as the 4th and 5th thread would wait forever. If your application anticipates a max to be bypassed under certain circumstance, maybe you've to use try-catch to capture the exception. I don't know...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top