title: How to write to COM port and wait for a reply c#
body: <p>I need to send commands to a serial port to communicate with a Enfora modem. For every command, I will get a reply but the length of the reply string may vary.
  I need to know how write and then wait for the reply until it finishes...</p>
  
  <p>So i thought of making a thread that reads from the serial port and the program only writes...</p>
  
  <p>The thread function</p>
  
  <pre><code>private void thread_Handler()
  {
      while(true)
          this.read();
  }
  private void read()
  {
      if (this.rtbMessages.InvokeRequired)
      {
          try
          {
              SetTextCallback d = new SetTextCallback(read);
              this.Invoke(d);
          }
          catch{}
      }
      else
      {
          readBuffer = serialPort.ReadExisting();
          rtbMessages.AppendText(readBuffer);
      }
  }
  </code></pre>
  
  <p>So this thread is always trying to read from the com PORT and I send the messages this way</p>
  
  <pre><code>writeBuffer = "COMMAND 1";
  serialPort.Write(writeBuffer);
  writeBuffer = "COMMAND 2";
  serialPort.Write(writeBuffer);
  </code></pre>
  
  <p>However I don't get the reply from the second command I send with Write()...
  I tried removing the thread and using ReadExisting() after every Write() but that also didn't work.</p>
  
  <p>The only way I could get it to work was to add a </p>
  
  <pre><code>System.Threading.Thread.Sleep(1000);
  </code></pre>
  
  <p>after every call to Write, then I get all the replies from every Write() command...
  But I don't want to use this, I want to know of another way to effectively write and get every reply from every command I send regardless of the length of the reply string and how long it takes for me to receive the reply message. </p>
  
  <p>Sometimes I will keep getting messages forever until I send another command to stop generating messages.</p>
  
  <p>Thank you!</p>