title: Monitoring multiple com ports using C#
body: <p>Background: we are developing an application (or windows service) that will listen for communications from various devices connected via virtual serial ports. Each device's information will be captured manually, so I know device 1 will be on COM5, Device 2 is on COM6, etc. Any time a device transmits data, I need to capture it and write in somewhere else (basically a log file).</p>
  
  <p>With that in mind, is it possible to monitor more than one serial port on a single thread, or should I spawn a new thread for each port (keep in mind that I know exactly which ports to monitor)?</p>
  
  <p>Or what would you guys think is a good approach?</p>
  
  <p>My working prototype code looks like this (only reads one port though):</p>
  
  <pre><code>class Program
      {
          public static void Main()
          {
              SerialPort mySerialPort = new SerialPort("COM5");
  
              mySerialPort.BaudRate = 9600;
              mySerialPort.Parity = Parity.None;
              mySerialPort.StopBits = StopBits.One;
              mySerialPort.DataBits = 8;
              mySerialPort.Handshake = Handshake.None;
  
              mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
  
              mySerialPort.Open();
  
              Console.WriteLine("Press any key to continue...");
              Console.WriteLine();
              Console.ReadKey();
  
              mySerialPort.Close();
          }
  
          private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
          {
              SerialPort sp = (SerialPort)sender;
              string indata = sp.ReadExisting();
              Console.WriteLine(indata);
              Debug.Print("Data Received:");
              Debug.Print(indata);
          }
      }
  </code></pre>
  
  <p>I'm basically wondering if I should create a class for each port that contains the code in the console application, or if I should go old-school and write a giant procedural app that monitors all of them at once.</p>