john
john

Reputation: 4433

Closing a SerialPort instance inside a class

I have created a library class for a control circuit which communicates through a serial port and is used in WinForms. When the class is initialized the serial port is opened

CircuitController controller = new CircuitController("Controller1", COM8, Baud9600, ...);

But what is the appropriate way to close the serial port when I exit the WinForm application? Should this be called on the controller specifically

(On close) --> controller.Shutdown();

Or will the serial port automatically close when the Form is closed?

Upvotes: 1

Views: 298

Answers (2)

Brad
Brad

Reputation: 163548

Per ildjarn's suggestion:

The best thing to do here is implement IDisposable, and close your port there. You can find some excellent example code for doing this on MSDN:

http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

Upvotes: 2

Raggles
Raggles

Reputation: 33

In my experience the port will close when the program exits (all handles opened by a process are closed by the os when the process exits as far as I understand), but I'm sure most will agree that it is best practice to close the port explicitly, as per your first suggestion.

Upvotes: 0

Related Questions