diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index 3293f2e..1836c73 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -30,6 +30,7 @@ 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; @@ -151,6 +152,7 @@ public partial class SerialPort : IDisposable _rxException = null; _rxExceptionReported = false; + _cts = new CancellationTokenSource(); _rxThread = new Thread(ReceiveThread) { Name = "CommBaseRx", Priority = ThreadPriority.AboveNormal, IsBackground = true @@ -186,10 +188,12 @@ public partial class SerialPort : IDisposable private void InternalClose() { + _cts.Cancel(); PInvoke.CancelIo(_hPort); + if (_rxThread != null) { - _rxThread.Abort(); + _rxThread.Join(); _rxThread = null; } @@ -461,7 +465,7 @@ public partial class SerialPort : IDisposable try { - while (true) + while (!_cts.IsCancellationRequested) { COMM_EVENT_MASK eventMask = 0;