Threading race conditions and using a timer to wake a thread

102 Views Asked by At

I have a C# console application with a consumer and a provider thread and a queue. The consumer is in a perpetual loop, that is blocked by a manualresetevent. The provider thread puts an object into the queue and signals the manualrestevent to unblock. The consumer receives the object from the queue, processes it and checks the queue for further objects. If the queue is empty the consumer resets the manualresetevent.

The problem I've found is that between the time the consumer checks the queue and resets the manualresetevent, the provider may load the queue and send a set signal before before the manualresetevent is reset, thus hanging the application.

I thought about using a timer to wake thread every few seconds to check the queue, is this a sound way to deal with this issue?

1

There are 1 best solutions below

0
On

Reset the ManualResetEvent before examining the queue, then don't go back to the point where you wait on the event until the queue has been drained. That way the worse thing a race can do is cause a single spurious check on an empty queue.

Or since you're now going to be resetting it immediately, use an AutoResetEvent instead.

Or indeed, if you can, use a BlockingCollection and let it handle the synchronisation for you.