Compare commits
2 Commits
v1.1.0-pre
...
master
Author | SHA1 | Date | |
---|---|---|---|
cb7f331b6a | |||
1101b71faf |
@ -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;
|
||||
@ -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
|
||||
@ -175,21 +177,25 @@ public partial class SerialPort : IDisposable
|
||||
/// </summary>
|
||||
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()
|
||||
{
|
||||
PInvoke.CancelIo(_hPort);
|
||||
|
||||
if (_rxThread != null)
|
||||
{
|
||||
_rxThread.Abort();
|
||||
_cts.Cancel();
|
||||
_rxThread.Join();
|
||||
_rxThread = null;
|
||||
}
|
||||
|
||||
@ -403,6 +409,9 @@ public partial class SerialPort : IDisposable
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked when a single character has been received.
|
||||
/// </summary>
|
||||
public event Action<byte> DataReceived;
|
||||
|
||||
/// <summary>
|
||||
@ -461,7 +470,7 @@ public partial class SerialPort : IDisposable
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
while (!_cts.IsCancellationRequested)
|
||||
{
|
||||
COMM_EVENT_MASK eventMask = 0;
|
||||
|
||||
@ -478,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
|
||||
{
|
||||
|
@ -20,5 +20,7 @@ internal class Program
|
||||
serialPort.Write("START\r\n");
|
||||
|
||||
Console.ReadKey();
|
||||
|
||||
serialPort.Close();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user