In my .NET Core console app I use collection of ClientWebSocket objects to receive some data. When something goes wrong and an exception occurs I'd like to close all websockets.
I tried to do this in such way:
foreach (var socket in _sockets)
{
if (socket.State == WebSocketState.Open || socket.State == WebSocketState.Connecting)
{
socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
}
}
But in case of socket.State == WebSocketState.Connecting
there is an exception:
System.AggregateException: 'One or more errors occurred. (The WebSocket is in an invalid state ('Connecting') for this operation. Valid states are: 'Open, CloseReceived, CloseSent')'
I know that I can use socket.Abort()
for WebSocketState.Connecting
as well as for WebSocketState.Open
.
The question is whether it will be the most proper way to close the connections - by using CloseAsync
for WebSocketState.Open
and Abort
for WebSocketState.Connecting
?