Fixed PlatformNotSupportedException on close

This commit is contained in:
Benjamin Höglinger-Stelzer 2024-07-14 10:29:06 +02:00
parent 582412f4dc
commit 1101b71faf

View File

@ -30,6 +30,7 @@ public partial class SerialPort : IDisposable
private Exception _rxException; private Exception _rxException;
private bool _rxExceptionReported; private bool _rxExceptionReported;
private Thread _rxThread; private Thread _rxThread;
private CancellationTokenSource _cts;
private int _stateBrk = 2; private int _stateBrk = 2;
private int _stateDtr = 2; private int _stateDtr = 2;
private int _stateRts = 2; private int _stateRts = 2;
@ -151,6 +152,7 @@ public partial class SerialPort : IDisposable
_rxException = null; _rxException = null;
_rxExceptionReported = false; _rxExceptionReported = false;
_cts = new CancellationTokenSource();
_rxThread = new Thread(ReceiveThread) _rxThread = new Thread(ReceiveThread)
{ {
Name = "CommBaseRx", Priority = ThreadPriority.AboveNormal, IsBackground = true Name = "CommBaseRx", Priority = ThreadPriority.AboveNormal, IsBackground = true
@ -186,10 +188,12 @@ public partial class SerialPort : IDisposable
private void InternalClose() private void InternalClose()
{ {
_cts.Cancel();
PInvoke.CancelIo(_hPort); PInvoke.CancelIo(_hPort);
if (_rxThread != null) if (_rxThread != null)
{ {
_rxThread.Abort(); _rxThread.Join();
_rxThread = null; _rxThread = null;
} }
@ -461,7 +465,7 @@ public partial class SerialPort : IDisposable
try try
{ {
while (true) while (!_cts.IsCancellationRequested)
{ {
COMM_EVENT_MASK eventMask = 0; COMM_EVENT_MASK eventMask = 0;