Owin.WebSocket
Owin.WebSocket copied to clipboard
High CPU usage when message size is exceeded
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.
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.