views:

415

answers:

1

I'm using a single producer-single consumer model with a blocking queue. I would like for the producer, when it has finished producing, to wait for the queue to empty before returning.

I implemented the BlockingQueue suggested here by Marc Gravell.

In my model, the producer (renderer) is using events to notify the worker (printer) when a file has is being rendered (worker queues the item) and when every file has been rendered (finished).

Right now, when the renderer is done, the method ends and the worker gets killed, so I end up with 10-15 rendered files that haven't been printed.

I want the finished event handler to block until the queue has been emptied, e.g., when all the files are printed. I want to add something like a "WaitToClose()" method that will block until the queue is empty.

(Would having the worker thread set to IsBackground = true make a difference?)

+2  A: 

How about adding an event to the queue:

private AutoResetEvent _EmptyEvent = new AutoResetEvent(false);

Then modify the Queue to set the event when it is empty, and you can block on the event.

Thinking it through further, however, when the queue is empty, the printer will still be printing the last item.

So, then you could join (block) on the worker thread.

Simpler idea: just block on the worker thread, and have the work thread finish (exit) when the queue is empty?

Alex Black
Wow... I should have thought of that. I just did a Join on the worker thread after calling the Close() method and poof... perfect.
Chris Thompson
Nice. Glad that worked.
Alex Black