title: .NET SerialPort DataReceived event thread interference with main thread
body: <p>I am writing a serial communication program using the SerialPort class in C# to interact with a strip machine connected via a RS232 cable. When I send the command to the machine it responds with some bytes depending on the command. Like when I send a "\D" command, I am expecting to download the machine program data of 180 bytes as a continuous string. As per the machine's manual, it suggests as a best practice to send an unrecognized characters like comma (,) character to make sure the machine is initialized before sending the first command in the cycle. My serial communication code is as follows:</p>
  
  <pre><code>public class SerialHelper
  {
      SerialPort commPort = null;
      string currentReceived = string.Empty;
      string receivedStr = string.Empty;
      private bool CommInitialized()
      {
          try
          {
              commPort = new SerialPort();
              commPort.PortName = "COM1";
              if (!commPort.IsOpen)
                  commPort.Open();
              commPort.BaudRate = 9600;
              commPort.Parity = System.IO.Ports.Parity.None;
              commPort.StopBits = StopBits.One;
              commPort.DataBits = 8;
              commPort.RtsEnable = true;
              commPort.DtrEnable = true;
  
              commPort.DataReceived += new SerialDataReceivedEventHandler(commPort_DataReceived);
              return true;
          }
          catch (Exception ex)
          {
              return false;
          }
      }
  
      void commPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
          SerialPort currentPort = (SerialPort)sender;
          currentReceived = currentPort.ReadExisting();
          receivedStr += currentReceived;
      }
  
      internal int CommIO(string outString, int outLen, ref string inBuffer, int inLen)
      {
          receivedStr = string.Empty;
          inBuffer = string.Empty;
          if (CommInitialized())
          {
              commPort.Write(outString);
          }
  
          System.Threading.Thread.Sleep(1500);
  
          int i = 0;
          while ((receivedStr.Length &lt; inLen) &amp;&amp; i &lt; 10)
          {
              System.Threading.Thread.Sleep(500);
              i += 1;
          }
  
          if (!string.IsNullOrEmpty(receivedStr))
          {
              inBuffer = receivedStr;
          }
          commPort.Close();
  
          return inBuffer.Length;
  
      }
  }
  </code></pre>
  
  <p>I am calling this code from a windows form as follows:</p>
  
  <pre><code>len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4)
  len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4)
  If(inBuffer == "!?*O")
  {
     len = SerialHelperObj.CommIO("\D",2,ref inBuffer, 180)
  }
  </code></pre>
  
  <p>A valid return value from the serial port looks like this:
  \D00000010000000000010 550 3250 0000256000 and so on ...</p>
  
  <p>I am getting something like this:
  \D00000010D,, 000 550 D,, and so on...</p>
  
  <p>I feel that my comm calls are getting interfered with the one when I send commands. But I am trying to make sure the result of the comma command then initiating the actual command. But the received thread is inserting the bytes from the previous communication cycle. </p>
  
  <p>Can anyone please shed some light into this...? 
  I lost quite some hair just trying to get this work. I am not sure where I am doing wrong</p>