How do I make ClientWebSocket.ReceiveAsync timeout in 5 seconds only if the web socket client is not connected? The current behavior is that it timeouts no matter what conditions are met, i.e. whether the web socket client is connected or not, which is not the behavior I expect.

var timeOut = new CancellationTokenSource(5000).Token;
var receiveResult = await _clientWebSocket.ReceiveAsync(buffer.Memory, timeOut).ConfigureAwait(false);
1

There are 1 best solutions below

1
On

Set the keep alive interval to 5 secs:

_clientWebSocket.Options.KeepAliveInterval = TimeSpan.FromSeconds(5);