title: C# COM port communication problem
body: <p>I have a C# code which communicates with three different COM ports. The COM ports are actually three serial port to USB converters. </p>
  
  <p>The code each time switches 'off' and 'on' the devices to which it is communicating, then initializes the three com ports, tries to send and read data and then closes the com port. This keeps continuing for a pre-defined number of loops.
  My problem is that after about 8 or 9 iterations, the COM port communication stops working. Sometime it throws an error saying the port is closed, sometime it does not throw any exception but it is actually not reading or writing anything from the com port. Some point it was only writing but not reading back the data.</p>
  
  <p>What might be the reason and any tips to debug this problem?</p>
  
  <p>EDIT:</p>
  
  <p>The port abruptly closes or stops working even in the middle of the program as shown below:</p>
  
  <pre><code>SerialPort.Write("ss");
  SerialPort.Read("ss"); // FAILS!!
  </code></pre>
  
  <p>Some part of the code I am using</p>
  
  <pre><code>public string Read(string readCommand)
          {
              string str = "";
              _port.WriteLine("\r");
              _port.WriteLine(readCommand + "\r");
              Thread.Sleep(0x3e8);
              str = _port.ReadExisting();
              return str;
          }
  
  public void Write(string command)
          {
              _port.WriteLine(command + "\r");
              Thread.Sleep(100);
              if (_port.ReadExisting() == string.Empty)
              {
                  throw new IOException("Error writing to COM");
              }
          }
  
      public void Initialize()
      {
          if (_port == null)
          {
              _port = new SerialPort(this.PortName.ToString(), this.BaudRate, this.Parity, this.DataBits, this.StopBits);
              _port.Handshake = this.Handshake;
          }
          try
          {
              if (!_port.IsOpen)
              {
                  _port.Open();
                  if (Read("") == string.Empty)
                  {
                      throw new IOException("Device not connected or powered on");
                  }
  
              }
          }
          catch (Exception)
          {
              this.Close();
          }
      }
  </code></pre>
  
  <p>Thanks...</p>