title: C# Serial port send and wait for recieve
body: <p>I have some commands that I stored into list. I need to go thrue list, send command and wait a reply for specific time (time is also in the list).</p>
  
  <p>This is my code:</p>
  
  <pre><code>SerialPort myPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
  
  bool _doSend;
  string _inSensor;
  int _threadWait;
  
  Thread myThread = new Thread(myStartingMethod);
  
  checkPortStatus();
  
  private void checkPortStatus()
  {
      if (!(myPort.IsOpen == true))
          {
              myPort.Open();
              myPort.DataReceived += new SerialDataReceivedEventHandler(myPort_DataReceived);
              _doSend = true;
              myThread.Start();
          }
          else
          {
              _doSend = false;
              myPort.Close();
              myThread.Abort();
          }
  }
  
  public void myStartingMethod()
      {
          //Create list of commands
          List&lt;List&lt;String&gt;&gt; atCommands = new List&lt;List&lt;string&gt;&gt;();
  
          //Create list of time to wait for informaition (recieve on setial port)
          List&lt;List&lt;String&gt;&gt; thSleep = new List&lt;List&lt;string&gt;&gt;();
  
          thSleep.Add(new List&lt;string&gt; { "1", "1000" }); //{"Sensor ID", "Time to wait for replay"}
          thSleep.Add(new List&lt;string&gt; { "2", "5000" });
  
          atCommands.Add(new List&lt;string&gt; { "1", "A111", "B111"});  //{"Sensor ID", "command 1", "command 2"}
          atCommands.Add(new List&lt;string&gt; { "2", "C222", "D222"});
          atCommands.Add(new List&lt;string&gt; { "1", "A111", "B111", "E111", "F111"});  
          atCommands.Add(new List&lt;string&gt; { "2", "D111"});
  
          while(_doSend)
          {
              foreach (var _subList in thSleep)
              {
                  _inSensor = _subList.ElementAt(0);
                  _threadWait = Convert.ToInt32(_subList.ElementAt(1));
  
                  foreach(var subCommands in atCommands)
                  {
                       if(_inSensor == subCommand.AlementAt(0)
                       {
                          foreach (string command in subCommands.Skip(1))
                          {
                              myPort.Write(command + "\r\n");
  
                              Thread.Sleep(_threadWait);
                          }
                       }
                  }
              }
  
          }
      }
  void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
          //Do something with data and save to Database
      }
  </code></pre>
  
  <p>My question is: How to be 100% sure that I got reply on command that I sent. If there is no reply within the given time I need to go on other command. In "myPort_DataReceived" I would like to store last sent command and recieved data to mySql database.
  I know how to connect to database but I have a problem with wait for response.</p>