Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I call SerialPort.Dispose() vs SerialPort.Close()?

Tags:

c#

dispose

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;
    }
}
like image 412
Lauraducky Avatar asked Jan 23 '18 04:01

Lauraducky


2 Answers

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 );
    }
like image 53
Rawitas Krungkaew Avatar answered Nov 12 '22 08:11

Rawitas Krungkaew


Close is the same thing as Dispose for this class. Using ILSpy, this is the code for the Close method:

public void Close()
{
    base.Dispose();
}
like image 27
Titian Cernicova-Dragomir Avatar answered Nov 12 '22 07:11

Titian Cernicova-Dragomir