views:

80

answers:

3

In .NET, is there a way to get the count on a semaphore. I don't need a threadsafe count, just a reasonable approximation so report the status on a GUI thread.

Currently I'm using a dual-counter. The real semaphore and another variable that is incremented and decremented in sync, but this is annoying and error prone.

A: 

No. To do this you would have to wrap (subclass) Semaphore into something with a counter. Since you don't care about thread safety it won't be that hard.

Dan Lorenc
Sigh, I was afraid you were going to say that.
Jonathan Allen
+2  A: 

Instead of the Semaphore, you could use Interlocked.Increment and Interlocked.Decrement. This will allow you to read the current value easily, since it's a regular variable.

If you use it in conjunction with some kind of Mutex for the situation where the count reaches 0, that should get the job done. Inheriting from your chosen mutex or WaitHandle will get you a nice reusable component.

See the Interlocked class.

Thorarin
You just described what I said I was already doing.
Jonathan Allen
Then what's the problem? It's not inherently error prone, though you'd probably have to move away from using Interlocked and use another lock instead. If your implementation is having a problem, then post it on SO.As for annoying.. well, sometimes you have to write some code of your own.
Thorarin
A: 

Process Explorer does it, somehow. It probably involves deep windows API magic, because it extracts the maximum count as well as the current count.

You can also try the moral equivalent of

int old_count=0;
if (AcquireSemaphore(timeout=0)) {
  ReleaseSemaphore(&old_count);
  old_count += 1;
}

but this has the caveat that it is lightly intrusive to code that uses the semaphore.

Paul Du Bois