I have a SerialPort
that I'm using to connect to a virtual COM port. Since the connection is persistent, I'm having to keep a reference to the SerialPort
in order to open, close, and otherwise manage the port. I'm also implementing IDisposable
on my class (not the full Dispose pattern, as I don't actually have any proper unmanaged resources, just the SerialPort
).
My question has to do with the use of SerialPort.Dispose()
vs SerialPort.Close()
. I'm using Close()
in several places, and I understand from the documentation that this calls the Dispose()
method on the SerialPort
. However, what if, as in my TryConnect()
method, it is possible that the SerialPort
was never opened? Should I simply call Dispose()
, and leave it at that? Or is the Close()
method a better option?
More broadly, is it always a good idea to use one of these methods over the other?
Some relevant snippets from my code are below.
public bool TryConnect() {
CheckDisposed();
try {
connectedPort = new SerialPort(SelectedPort);
connectedPort.WriteTimeout = 1000;
connectedPort.DataReceived += P_DataReceived;
connectedPort.Open();
return true;
} catch (Exception e) {
if (connectedPort != null) {
connectedPort.Dispose();
connectedPort = null;
}
return false;
}
}
public void Disconnect() {
CheckDisposed();
if (connectedPort != null) {
connectedPort.Close();
connectedPort = null;
}
}
public void Dispose() {
if (!disposed) {
if (connectedPort != null) {
connectedPort.Close();
connectedPort = null;
}
disposed = true;
}
}
Calling Close
is equal to calling Dispose(true)
https://github.com/Microsoft/referencesource/blob/master/System/sys/system/IO/ports/SerialPort.cs
// Calls internal Serial Stream's Close() method on the internal Serial Stream.
public void Close()
{
Dispose();
}
protected override void Dispose( bool disposing )
{
if( disposing ) {
if (IsOpen) {
internalSerialStream.Flush();
internalSerialStream.Close();
internalSerialStream = null;
}
}
base.Dispose( disposing );
}