Chris Thompson
Chris Thompson

Reputation: 16861

How to wait for a Blocking Queue to be emptied by worker

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?)

Upvotes: 4

Views: 2394

Answers (1)

waterlooalex
waterlooalex

Reputation: 13892

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?

Upvotes: 4

Related Questions