0

I have a bunch of threads producing objects (e.g. strings) and a single thread consuming batch of objects (e.g. serializing them and sending yo a remote server).

I want producers to be able to pish data as fast as possible. They should never lock because of other producers, not even by the consumer. Is this possible? How?

Igor Gatis
  • 4,648
  • 10
  • 43
  • 66
  • This seems te be a job for `ConcurrentQueue`, but the requirement "*they should never lock*" is a bit unclear. If you are working multithreaded and are willing to create a collection which is accessibly by multiple threads, your arw definitely going to need locks. – Dion V. Dec 30 '14 at 20:36
  • Perhaps `BlockingCollection` ? and what do you mean by *They should never lock* ? and what about *Thread safety* concerns ? – Sriram Sakthivel Dec 30 '14 at 20:38
  • ConcurrentBag has this concept of per thread list. AFAIK, multiple Add calls will never block. A consumer could use a interlock swap to consume each thread list. I wonder whether c# has something built in already. – Igor Gatis Dec 30 '14 at 20:43

1 Answers1

1

You can use a BlockingCollection, which by default wraps a ConcurrentQueue.

BlockingCollection is a thread-safe collection class that provides the following features:

An implementation of the Producer-Consumer pattern.

Concurrent adding and taking of items from multiple threads.

Ani
  • 111,048
  • 26
  • 262
  • 307