1313namespace Communication
1414{
1515 /// <inheritdoc />
16- internal sealed class SystemSerialPort : ISerialPort
16+ internal sealed class SystemSerialPort : ISerialPort , IDisposable
1717 {
18+ /// <summary>
19+ /// The port
20+ /// </summary>
1821 private readonly SerialPort _port ;
1922
23+ /// <summary>
24+ /// The disposed
25+ /// </summary>
26+ private bool _disposed ;
27+
2028 /// <inheritdoc />
2129 public event EventHandler ? DataReceived ;
2230
@@ -42,8 +50,17 @@ public SystemSerialPort(string portName, SerialPortConfig cfg)
4250 WriteTimeout = - 1
4351 } ;
4452
45- _port . DataReceived += ( _ , __ ) =>
46- DataReceived ? . Invoke ( this , EventArgs . Empty ) ;
53+ _port . DataReceived += OnDataReceived ;
54+ }
55+
56+ /// <summary>
57+ /// Called when [data received].
58+ /// </summary>
59+ /// <param name="sender">The sender.</param>
60+ /// <param name="e">The <see cref="SerialDataReceivedEventArgs"/> instance containing the event data.</param>
61+ private void OnDataReceived ( object sender , SerialDataReceivedEventArgs e )
62+ {
63+ DataReceived ? . Invoke ( this , EventArgs . Empty ) ;
4764 }
4865
4966 /// <inheritdoc />
@@ -67,5 +84,25 @@ public void Write(string data)
6784 /// <inheritdoc />
6885 public void Write ( byte [ ] buffer , int offset , int count )
6986 => _port . Write ( buffer , offset , count ) ;
87+
88+ /// <summary>
89+ /// Cleanup the hardware port.
90+ /// </summary>
91+ public void Dispose ( )
92+ {
93+ if ( _disposed ) return ;
94+
95+ // Unhook event to avoid memory leaks
96+ _port . DataReceived -= OnDataReceived ;
97+
98+ // Close and Dispose the actual hardware port
99+ if ( _port . IsOpen )
100+ {
101+ _port . Close ( ) ;
102+ }
103+
104+ _port . Dispose ( ) ;
105+ _disposed = true ;
106+ }
70107 }
71108}
0 commit comments