classic producer consumer pattern using blockingcollection and tasks .net 4 TPL classic producer consumer pattern using blockingcollection and tasks .net 4 TPL multithreading multithreading

classic producer consumer pattern using blockingcollection and tasks .net 4 TPL


You would use BlockingCollection<T>. There's an example in the documentation.

That class is specifically designed to make this trivial.


Your second block of code looks better. But, starting a Task and then immediately waiting on it is pointless. Just call Take and then process the item that is returned directly on the consuming thread. That is how the producer-consumer pattern is meant to be done. If you think the processing of work items is intensive enough to warrant more consumers then by all means start more consumers. BlockingCollection is safe multiple producers and multiple consumers.

public class YourCode{  private BlockingCollection<object> queue = new BlockingCollection<object>();  public YourCode()  {    var thread = new Thread(StartConsuming);    thread.IsBackground = true;    thread.Start();  }  public void Produce(object item)  {    queue.Add(item);  }  private void StartConsuming()  {    while (true)    {      object item = queue.Take();      // Add your code to process the item here.      // Do not start another task or thread.     }  }}


I've used a pattern before that creates a sort of 'on-demand' queue consumer (based on consuming from a ConcurrentQueue):

        private void FireAndForget(Action fire)        {            _firedEvents.Enqueue(fire);            lock (_taskLock)            {                if (_launcherTask == null)                {                    _launcherTask = new Task(LaunchEvents);                    _launcherTask.ContinueWith(EventsComplete);                    _launcherTask.Start();                }            }        }        private void LaunchEvents()        {            Action nextEvent;            while (_firedEvents.TryDequeue(out nextEvent))            {                if (_synchronized)                {                    var syncEvent = nextEvent;                    _mediator._syncContext.Send(state => syncEvent(), null);                }                else                {                    nextEvent();                                        }                lock (_taskLock)                {                    if (_firedEvents.Count == 0)                    {                        _launcherTask = null;                        break;                    }                }            }        }        private void EventsComplete(Task task)        {            if (task.IsFaulted && task.Exception != null)            {                 // Do something with task Exception here            }        }