Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should be able to do these simultaneously (assuming that's ok). You would then close them as the <code>DataReceived</code> event is raised (extraneous code removed). Just don't close the port in <code>CheckPorts</code>.</p> <pre><code>private void testSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort localSerialPort = sender as SerialPort; ... // use localSerialPort instead of global/class variable if (localSerialPort.IsOpen) { localSerialPort.Close(); } } </code></pre> <p><strong>EDIT</strong>: Responding to comment.</p> <p>You can always add a timer on the fly. If you put this in the foreach loop, you'll get a timer for every serial port that will dispose its given serial port after 3 seconds. It's important here that the timer is declared within the foreach loop.</p> <pre><code>var interval = 3000; // ms var timer = new System.Timers.Timer(interval); timer.Elapsed += (o,e) =&gt; { timer.Enabled = false; if (testSerial.IsOpen) testSerial.Close(); // may not be necessary with Dispose? testSerial.Dispose(); timer.Dispose(); } timer.Enabled = true; </code></pre> <p><strong>EDIT</strong>: Code updated so I'll update</p> <p>Scope is very important with the code I provided. You should get rid of the non-local testSerial or use an entirely different name here.</p> <pre><code> portNumber = Int32.Parse(s.Remove(0, 3)); // MUST BE LOCAL var serialOneOfMany = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One); serialOneOfMany.ReadTimeout = 2000; serialOneOfMany.WriteTimeout = 2000; if (serialOneOfMany.IsOpen) { serialOneOfMany.Close(); } // timer must be defined _after_ serialOneOfMany var interval = 3000; // ms var timer = new System.Timers.Timer(interval); timer.Elapsed += (o, e) =&gt; { timer.Enabled = false; if (serialOneOfMany.IsOpen) serialOneOfMany.Close(); // may not be necessary with Dispose? serialOneOfMany.Dispose(); timer.Dispose(); }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload