infinite producers and blockingcollection question RRS feed

  • Question

  • I am developing a custom windows service that communicates over the serial port to some custom hardware.

    I have multiple threads and been having quite a hard time getting them to write to the serial port without stepping on each other.  Recent guidance says don't do that .  Use BlockingCollection and a single thread that writes/reads the serial port.  In essence the BlockingCollection is the command queue for the serial port.

    When the service starts it launches a thread which is a polling loop (infinite) which sends a command to the serial port to get data from the hardware.  It starts another thread which listens on a socket for a diagnostic command, this also is infinite.

    So, I have (2) infinite producers and 1 consumer.  Is this possible using BlockingCollection ?

    Thanks a million.

    Thursday, October 10, 2019 2:22 PM

All replies

  • When a command is sent, is there always a reply?  Will the hardware ever send anything on its own, without a command?  If it's always a one-in, one-out situation, then you don't need a collection at all, nor do you need a continuously polling thread.  You just need to use locks.

        string SendCommand( string input )
            lock( this )
                 send-to-hardware( input );
                 return read-from-hardware();

    The lock will insure that each command is atomic and serialized.  If another thread tries to send a command while the previous command is still outstanding, it will block at the "lock" statement.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Thursday, October 10, 2019 6:00 PM
  • there are multiple examples for "BlockingCollection Producer Consumer" online.
    I used a consumer with foreach loop over BlockingCollection<T>.GetConsumingEnumerable,
    and multiple producers Adding
    BlockingCollection in the Foreach loop
    Thursday, October 10, 2019 7:39 PM
  • Thanks for the idea.  I do need polling as the equipment is continuously collecting external data that needs to be stuffed in a database.

    so thread 1 polls, thread 2 diagnostic thread 3 send/receive with lock right ?

    Friday, October 11, 2019 12:59 PM
  • you don't need additional locks. BlockingCollection is already used with thread-safe collections.
    but look at the examples.
    Friday, October 11, 2019 1:36 PM