You do not need to do a full mutex, but can you put a lock statement
public void AddWork(WorkToDo work) { queue.Add(work); lock(lockingObject) { signal.Set(); } }
use whatever you want for the lock object, most people will say that using the signal itself is a bad idea.
Responding to a comment @ 500 - Internal server error below, you can simply reset to transmit a signal before doing the job. The following should protect things:
while(ApplicationIsRunning) { while(queue.HasWork) { WorkItem wi; lock(lockingObject) { wi = queue.NextWorkItem; if(!queue.HasWork) { signal.Reset(); } } DoWork(wi) } signal.WaitOne(); }
Thus, if you have more work, the internal queue continues. If not, then it drops to signal.WaitOne() , and we only reset if there is no more work in the queue.
The only drawback here is that we can reset several times in a row if work comes in when DoWork is DoWork .
source share