Proper way to have an endless worker thread? Proper way to have an endless worker thread? multithreading multithreading

Proper way to have an endless worker thread?


You need to lock anyway, so you can Wait and Pulse:

while(true) {    SomeType item;    lock(queue) {        while(queue.Count == 0) {            Monitor.Wait(queue); // releases lock, waits for a Pulse,                                 // and re-acquires the lock        }        item = queue.Dequeue(); // we have the lock, and there's data    }    // process item **outside** of the lock}

with add like:

lock(queue) {    queue.Enqueue(item);    // if the queue was empty, the worker may be waiting - wake it up    if(queue.Count == 1) { Monitor.PulseAll(queue); }}

You might also want to look at this question, which limits the size of the queue (blocking if it is too full).


You need a synchronization primitive, like a WaitHandle (look at the static methods) . This way you can 'signal' the worker thread that there is work. It checks the queue and keeps on working until the queue is empty, at which time it waits for the mutex to signal it again.

Make one of the job items be a quit command too, so that you can signal the worker thread when it's time to exit the thread


In most cases, I've done this quite similar to how you've set up -- but not in the same language. I had the advantage of working with a data structure (in Python) which will block the thread until an item is put into the queue, negating the need for the sleep call.

If .NET provides a class like that, I'd look into using it. A thread blocking is much better than a thread spinning on sleep calls.

The job you can pass could be as simple as a "null"; if the code receives a null, it knows it's time to break out of the while and go home.