From b82d946af37d19cf19033ca63ff8be051bfee361 Mon Sep 17 00:00:00 2001 From: Darren Horrocks Date: Sat, 21 Oct 2023 00:09:43 +0100 Subject: [PATCH] fix threading/concurrency issue in TCP connection --- bzTorrent/IO/PeerWireTCPConnection.cs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/bzTorrent/IO/PeerWireTCPConnection.cs b/bzTorrent/IO/PeerWireTCPConnection.cs index c4790b3..8a0963a 100644 --- a/bzTorrent/IO/PeerWireTCPConnection.cs +++ b/bzTorrent/IO/PeerWireTCPConnection.cs @@ -35,6 +35,7 @@ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR using System.Text; using System; using System.Net; +using System.Collections.Concurrent; namespace bzTorrent.IO { @@ -45,8 +46,8 @@ public class PeerWireTCPConnection : IPeerConnection private byte[] currentPacketBuffer = null; private const int socketBufferSize = 16 * 1024; private readonly byte[] socketBuffer = new byte[socketBufferSize]; - private readonly Queue receiveQueue = new(); - private readonly Queue sendQueue = new(); + private readonly ConcurrentQueue receiveQueue = new(); + private readonly ConcurrentQueue sendQueue = new(); private PeerClientHandshake incomingHandshake = null; public int Timeout @@ -135,10 +136,12 @@ public bool Process() socket.BeginReceive(socketBuffer, 0, socketBufferSize, SocketFlags.None, ReceiveCallback, this); } - while(sendQueue.Count > 0) + while (sendQueue.Count > 0) { - var packet = sendQueue.Dequeue(); - socket.Send(packet.GetBytes()); + if (sendQueue.TryDequeue(out var packet)) + { + socket.Send(packet.GetBytes()); + } } return Connected; @@ -151,9 +154,9 @@ public void Send(PeerWirePacket packet) public PeerWirePacket Receive() { - if (receiveQueue.Count > 0) + if (receiveQueue.Count > 0 && receiveQueue.TryDequeue(out var packet)) { - return receiveQueue.Dequeue(); + return packet; } return null;