Owin.WebSocket icon indicating copy to clipboard operation
Owin.WebSocket copied to clipboard

High CPU usage when message size is exceeded

Open yahya99223 opened this issue 7 years ago • 1 comments

I have created a websocket using Owin.Websocket.WebSocketConnection to receive messages from my Frontend.

public class MyWebScoket : WebSocketConnection
{
   protected MyWebScoket(int maxMessageSize = 65536) : base(maxMessageSize)
   {
      //logic
   }
   public override void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
   {
       //logic
   }
   public override Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type)
   {
       //logic
   }
   public override void OnOpen()
   {
       //logic
   }
   public override void OnReceiveError(Exception error)
   {
       //logic
   }
}

When the message size is below the set message size, CPU usage of API is normal and everything is functioning as it should, however when the message size exceeds the limit, CPU usage of API increases dramatically, causing my machine to stop responding even to mouse clicks.

This seems strange, as the message sending rate is always the same.

What is the reason of such behavior?

I added breakpoints inside all overridden methods, but none of them is reached, I thought if the message limit size is exceeded the execution should go to OnReceiveError.

yahya99223 avatar Feb 12 '18 12:02 yahya99223

The problem is this:

public async Task<Tuple<ArraySegment<byte>, WebSocketMessageType>> ReceiveMessage(byte[] buffer, CancellationToken cancelToken)
{
    var count = 0;
    WebSocketReceiveResult result;
    do
    {
        var segment = new ArraySegment<byte>(buffer, count, buffer.Length - count);
        result = await mWebSocket.ReceiveAsync(segment, cancelToken);

        count += result.Count;
    }
    while (!result.EndOfMessage);

    return new Tuple<ArraySegment<byte>, WebSocketMessageType>(new ArraySegment<byte>(buffer, 0, count), result.MessageType);
}

If the buffer size is exceeded, count becomes the buffer size and segment.Count becomes 0. Then, it just loops forever.

pvginkel avatar Dec 19 '18 13:12 pvginkel