From 1101b71fafeab5b02c5af636da49d311d79c705d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Sun, 14 Jul 2024 10:29:06 +0200 Subject: [PATCH] Fixed PlatformNotSupportedException on close --- Nefarius.Peripherals.SerialPort/SerialPort.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) 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;