diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 1836c73..6c549ea 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -22,6 +22,7 @@ public partial class SerialPort : IDisposable private readonly ManualResetEvent _writeEvent = new(false); private bool _auto; private bool _checkSends = true; + private CancellationTokenSource _cts; private Handshake _handShake; private SafeFileHandle _hPort; @@ -30,7 +31,6 @@ public partial class SerialPort : IDisposable private Exception _rxException; private bool _rxExceptionReported; private Thread _rxThread; - private CancellationTokenSource _cts; private int _stateBrk = 2; private int _stateDtr = 2; private int _stateRts = 2; @@ -177,22 +177,24 @@ public partial class SerialPort : IDisposable /// public void Close() { - if (_online) + if (!_online) { - _auto = false; - BeforeClose(false); - InternalClose(); - _rxException = null; + return; } + + _auto = false; + BeforeClose(false); + InternalClose(); + _rxException = null; } private void InternalClose() { - _cts.Cancel(); PInvoke.CancelIo(_hPort); if (_rxThread != null) { + _cts.Cancel(); _rxThread.Join(); _rxThread = null; } @@ -407,6 +409,9 @@ public partial class SerialPort : IDisposable { } + /// + /// Invoked when a single character has been received. + /// public event Action DataReceived; /// @@ -482,7 +487,7 @@ public partial class SerialPort : IDisposable { if (Marshal.GetLastWin32Error() == (int)WIN32_ERROR.ERROR_IO_PENDING) { - sg.WaitOne(); + WaitHandle.WaitAny(new[] { sg, _cts.Token.WaitHandle }); } else { diff --git a/PInvokeSerialPort.Sample/Program.cs b/PInvokeSerialPort.Sample/Program.cs index 8ebda6f..8668ba6 100755 --- a/PInvokeSerialPort.Sample/Program.cs +++ b/PInvokeSerialPort.Sample/Program.cs @@ -20,5 +20,7 @@ internal class Program serialPort.Write("START\r\n"); Console.ReadKey(); + + serialPort.Close(); } } \ No newline at end of file