C# producer/consumer

The code is older than that – I wrote it some time before .NET 2.0 came out. The concept of a producer/consumer queue is way older than that though 🙂

Yes, that code is safe as far as I’m aware – but it has some deficiencies:

  • It’s non-generic. A modern version would certainly be generic.
  • It has no way of stopping the queue. One simple way of stopping the queue (so that all the consumer threads retire) is to have a “stop work” token which can be put into the queue. You then add as many tokens as you have threads. Alternatively, you have a separate flag to indicate that you want to stop. (This allows the other threads to stop before finishing all the current work in the queue.)
  • If the jobs are very small, consuming a single job at a time may not be the most efficient thing to do.

The ideas behind the code are more important than the code itself, to be honest.

Leave a Comment