views:

314

answers:

3

In other words I have a thread that starts and calls waitHandle.Set() multiple times. Then I start several threads and each is waiting on that WaitHandle. Will X of the them be signaled where X is the number of times the original thread called waitHandle.Set()?

Is there a structure that supports what I'm trying to accomplish more closely?

+1  A: 

It depends on the EventResetMode. If it is set to EventResetMode.AutoReset it will only release one thread. If it is 'EventResetMode.ManualReset' however it will release all threads blocked on the event.

Semaphore.Release(Int)

Where Int is the count would be one way to do this.

Matt Davison
Is there no way to get it to release X threads where X is the number of times `waitHandle.Set()` was called?
Orion Adrian
Yes. create it as Auto. What are you trying to do? I'm sure there is a better way if you could provide some more info. As mentioned below you could also use a Semaphore but something smells fishy.
Matt Davison
No, an auto-reset event is not appropriate here. You're relying on the thread that's calling Set to only call it once. If the event gets set twice before any thread has its wait satisfied, then only one waiting thread gets to run.
Rob Kennedy
+3  A: 

Maybe, but probably not.

An event can only be set or unset, if there is nothing to unset the event then repeated calls to Set will not change its state, unless it is an auto-reset event and there is at least one thread waiting on it. With a manual reset event any threads waiting (or starting to wait) will be released until something unsets the thread.

I think you will actually want a semaphore, which does have a count and supports setting n times to release n threads (even if some of those threads only start waiting after some of the calls to set).

Richard
Yes I want a semaphor. I remembered the mechanics of it, but not the name. It's been awhile since I've written low-level threading code for resource pools.
Orion Adrian
+1  A: 

As Richard stated, EventWaitHandles have only a single flag and cannot count the number of times Set has been called. The simpleminded solution of adding a count variable causes a race condition.

William Kempf has an article on why count variables don't work, and a solution using the .Net Monitor class.

Dour High Arch