title: Constantly reading from a serial port with a background thread
body: <p>As serial port communication is asynchronous, I figured out early on into my project involving communication with a RS 232 device that I will have to have a background thread constantly reading the port for data received. Now, I'm using IronPython (.NET 4.0) so I have access to the slick SerialPort class built into .NET. This lets me write code like this:</p>
  
  <pre><code>self.port = System.IO.Ports.SerialPort('COM1', 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One)
  self.port.Open()
  reading = self.port.ReadExisting() #grabs all bytes currently sitting in the input buffer
  </code></pre>
  
  <p>Simple enough. But as I mentioned I want to be constantly checking this port for new data as it arrives. Ideally, I would have the OS <em>tell</em> me anytime there's data waiting. Whaddaya know, my prayers have been answered, there is a <code>DataReceived</code> event provided!</p>
  
  <pre><code>self.port.DataReceived += self.OnDataReceived
  
  def OnDataReceived(self, sender, event):
      reading = self.port.ReadExisting()
      ...
  </code></pre>
  
  <p>Too bad this is worthless, though, <a href="http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx" rel="nofollow">because this event isn't guaranteed to be raised</a>! </p>
  
  <blockquote>
    <p>The DataReceived event is not guaranteed to be raised for every byte received. </p>
  </blockquote>
  
  <p>So back to writing a listener thread, then. I've accomplished this rather quickly with a <code>BackgroundWorker</code> that just calls <code>port.ReadExisting()</code> over and over again. It reads bytes as they come in, and when it sees a line ending (<code>\r\n</code>), it places what it read into a <code>linebuffer</code>. Then other parts of my program look at the <code>linebuffer</code> to see if there are any complete lines waiting to be used.</p>
  
  <p>Now, this is a classic <strong>producer-consumer</strong> problem, obviously. The producer is the <code>BackgroundWorker</code>, placing complete lines into <code>linebuffer</code>. The consumer is some code that consumes those lines from the <code>linebuffer</code> as fast as possible. </p>
  
  <p>However, the consumer is sort of inefficient. Right now he's constantly checking the <code>linebuffer</code>, getting disappointed each time to find it empty; though every once in a while does find a line waiting inside. What's the best way to optimize this so that the consumer only wakes up when there is a line available? That way the consumer isn't spinning around constantly accessing the <code>linebuffer</code>, which might introduce some concurrency issues.</p>
  
  <p>Also, if there is a simpler/better way of reading constantly from a serial port, I'm open to suggestions!</p>