Skip to content

Commit

Permalink
Replace queue with concurrent queue
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianstevens committed Nov 19, 2024
1 parent b74a9fe commit 5796786
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions Source/v2/Meadow.HCom/Connections/SerialConnection.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.IO.Ports;
using System.Security.Cryptography;

Expand All @@ -21,7 +22,7 @@ public partial class SerialConnection : ConnectionBase, IDisposable
private bool _isDisposed;
private ConnectionState _state;
private readonly List<IConnectionListener> _listeners = new List<IConnectionListener>();
private readonly Queue<IRequest> _pendingCommands = new Queue<IRequest>();
private readonly ConcurrentQueue<IRequest> _commandQueue = new ConcurrentQueue<IRequest>();
private readonly AutoResetEvent _commandEvent = new AutoResetEvent(false);
private bool _maintainConnection;
private Thread? _connectionManager = null;
Expand Down Expand Up @@ -208,8 +209,7 @@ public override void Detach()
// local function so we can unsubscribe
var count = _messageCount;

_pendingCommands.Enqueue(command);
_commandEvent.Set();
EnqueueRequest(command);

while (timeout-- > 0)
{
Expand Down Expand Up @@ -248,19 +248,17 @@ private void CommandManager()
{
_commandEvent.WaitOne(1000);

while (_pendingCommands.Count > 0)
while (_commandQueue.Count > 0)
{
Debug.WriteLine($"There are {_pendingCommands.Count} pending commands");
Debug.WriteLine($"There are {_commandQueue.Count} pending commands");

_commandQueue.TryDequeue(out var pendingCommand);

var command = _pendingCommands.Dequeue() as Request;
if (command != null)
if (pendingCommand is Request command)
{
// if this is a file write, we need to packetize for progress

var payload = command.Serialize();
EncodeAndSendPacket(payload);

// TODO: re-queue on fail?
}
}
}
Expand Down Expand Up @@ -297,7 +295,7 @@ public void EnqueueRequest(IRequest command)
};
}

_pendingCommands.Enqueue(command);
_commandQueue.Enqueue(command);
_commandEvent.Set();
}

Expand Down

0 comments on commit 5796786

Please sign in to comment.