Note that there are some explanatory texts on larger screens.

plurals
  1. PODisposing serial port object
    text
    copied!<p>I'm writing a small piece of code that would determine which serial ports on a computer are free for connection. This is done by looping through the different serial ports and calling the Open() method. If an exception occurs, this indicates that the port is unavailable.</p> <p>However visual studios is telling me that I'm not disposing of the object properly, or disposing it too many times if I place the dispose method within the finally block. What is the best way of disposing the serial port object, and is it wise to create a new serial port object in the for or leave it how it is?</p> <p>The commented section with the question marks is the bits that I'm unsure about.</p> <pre><code> public static void QueryOpenPorts(out string[] portNames, out bool[] isOpen) { // serial port object used to query SerialPort serialPort = new SerialPort(); // get valid ports on current computer portNames = SerialPort.GetPortNames(); // number of valid ports int count = portNames.Length; // initialise isOpen array isOpen = new bool[count]; // iterate through portNames and check Open() for (int i = 0; i &lt; count; i++) { // set port name serialPort.PortName = portNames[i]; // attempt to open port try { serialPort.Open(); // port available isOpen[i] = true; } catch (Exception ex) { // serial port exception if (ex is InvalidOperationException || ex is UnauthorizedAccessException || ex is IOException) { // port unavailable isOpen[i] = false; } } finally { // // close serial port if opened successfully ???????????? // if (serialPort.IsOpen) // { // serialPort.Close(); // } } } // release object ????????? // serialPort.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