Skip to content

Commit

Permalink
Use message queue instead of SemaphoreSlim - SemaphoreSlim was severe…
Browse files Browse the repository at this point in the history
…ly bottlenecking performance (MirrorNetworking#839)
  • Loading branch information
Katori authored and vis2k committed Apr 23, 2019
1 parent 2695da4 commit 5aa7148
Showing 1 changed file with 11 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
// ---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net.WebSockets;
Expand Down Expand Up @@ -57,7 +58,8 @@ internal class WebSocketImplementation : WebSocket
const int MAX_PING_PONG_PAYLOAD_LEN = 125;
WebSocketCloseStatus? _closeStatus;
string _closeStatusDescription;
SemaphoreSlim sendSemaphore = new SemaphoreSlim(1, 1);
bool sendingMessage = false;
Queue<ArraySegment<byte>> messagesToSend = new Queue<ArraySegment<byte>>();

public event EventHandler<PongEventArgs> Pong;

Expand Down Expand Up @@ -223,14 +225,15 @@ public override async Task SendAsync(ArraySegment<byte> buffer, WebSocketMessage
// In SslStream, only one SendAsync can be going at a time
// if Send is called multiple time, only the first one calls SendAsync,
// the other ones queue up the message
await sendSemaphore.WaitAsync();
try
{
await SendAsyncInternal(buffer, messageType, endOfMessage, cancellationToken);
}
finally
messagesToSend.Enqueue(buffer);
if (!sendingMessage)
{
sendSemaphore.Release();
sendingMessage = true;
while (messagesToSend.Count > 0)
{
await SendAsyncInternal(messagesToSend.Dequeue(), messageType, endOfMessage, cancellationToken);
}
sendingMessage = false;
}
}

Expand Down

0 comments on commit 5aa7148

Please sign in to comment.