Fix a crash with BlockingCollection in Connection

The BlockingCollection would have `IsAddingCompleted` to true, but `IsComplete` to false, slipping through the cracks and causing an InvalidOperationException ("The collection has been marked as complete with regards to additions.") when trying to add to it.
We now add a check on `(Try)SendData` to only try to add if we can. The collection is still viable for reading until empty/`IsComplete`.
This commit is contained in:
penev92
2022-06-04 10:30:21 +03:00
committed by Gustas
parent 2a681d3791
commit 216029dc27
2 changed files with 19 additions and 13 deletions

View File

@@ -154,10 +154,8 @@ namespace OpenRA.Server
// Regularly check player ping
if (lastPingSent.ElapsedMilliseconds > 1000)
{
sendQueue.Add(CreatePingFrame());
lastPingSent.Restart();
}
if (TrySendData(CreatePingFrame()))
lastPingSent.Restart();
// Send all data immediately, we will block again on read
while (sendQueue.TryTake(out var data, 0))
@@ -195,9 +193,21 @@ namespace OpenRA.Server
}
}
public void SendData(byte[] data)
public bool TrySendData(byte[] data)
{
sendQueue.Add(data);
if (sendQueue.IsAddingCompleted)
return false;
try
{
sendQueue.Add(data);
return true;
}
catch (InvalidOperationException)
{
// Occurs if the collection is marked completed for adding by another thread.
return false;
}
}
public void Dispose()

View File

@@ -434,7 +434,7 @@ namespace OpenRA.Server
var ms = new MemoryStream(8);
ms.WriteArray(BitConverter.GetBytes(ProtocolVersion.Handshake));
ms.WriteArray(BitConverter.GetBytes(newConn.PlayerIndex));
newConn.SendData(ms.ToArray());
newConn.TrySendData(ms.ToArray());
// Dispatch a handshake order
var request = new HandshakeRequest
@@ -737,14 +737,10 @@ namespace OpenRA.Server
void DispatchFrameToClient(Connection c, int client, byte[] frameData)
{
try
{
c.SendData(frameData);
}
catch (Exception e)
if (!c.TrySendData(frameData))
{
DropClient(c);
Log.Write("server", $"Dropping client {client.ToString(CultureInfo.InvariantCulture)} because dispatching orders failed: {e}");
Log.Write("server", $"Dropping client {client.ToString(CultureInfo.InvariantCulture)} because dispatching orders failed!");
}
}