@@ -41,6 +41,8 @@ class TextWebSocketClient : IWebSocketClient
4141 /// </summary>
4242 public event EventHandler < string > MessageReceived ;
4343
44+ private readonly object connectionLock = new object ( ) ;
45+
4446 /// <summary>
4547 /// Opens a WebSocket connection to the specified server URI and starts listening for messages.
4648 /// If the connection is already open or in a connecting state, this method does nothing.
@@ -52,7 +54,10 @@ class TextWebSocketClient : IWebSocketClient
5254 /// </returns>
5355 public async Task OpenAsync ( string serverUri , CancellationToken cancellationToken = default )
5456 {
55- webSocket ??= new ClientWebSocket ( ) ;
57+ lock ( connectionLock )
58+ {
59+ webSocket ??= new ClientWebSocket ( ) ;
60+ }
5661
5762 if ( webSocket . State != WebSocketState . Open && webSocket . State != WebSocketState . Connecting )
5863 {
@@ -92,14 +97,26 @@ private async Task ListenForMessages(CancellationToken cancellationToken)
9297 }
9398
9499 string message = Encoding . UTF8 . GetString ( buffer , 0 , result . Count ) ;
100+ Debug . WriteLine ( $ "Received message: { message } ") ;
95101 MessageReceived ? . Invoke ( this , message ) ;
96102 }
97103 }
98104 catch ( OperationCanceledException ex )
99105 {
100106 // Normal cancellation, no need to handle
101- Debug . WriteLine ( $ "ClientWebsocket connection was closed: { ex . Message } ") ;
107+ Debug . WriteLine ( $ "Websocket connection was closed: { ex . Message } ") ;
108+ }
109+ catch ( WebSocketException e )
110+ {
111+ // WebSocket error, notify the user
112+ Debug . WriteLine ( $ "Websocket error: { e . Message } ") ;
102113 }
114+ catch ( Exception e )
115+ {
116+ // Unexpected error, notify the user
117+ Debug . WriteLine ( $ "Unexpected error in Websocket listener: { e . Message } ") ;
118+ }
119+ Debug . WriteLine ( "Websocket ListenForMessage stopped" ) ;
103120 }
104121
105122 /// <summary>
@@ -123,7 +140,16 @@ private void StartListening(CancellationToken cancellationToken)
123140 }
124141
125142 await ListenForMessages ( cancellationToken ) ;
143+ Debug . WriteLine ( "Websocket listeningTask stopped" ) ;
126144 } , cancellationToken ) ;
145+
146+ _ = listeningTask . ContinueWith ( task =>
147+ {
148+ if ( ! task . IsFaulted )
149+ return ;
150+ Debug . WriteLine ( $ "Websocket listener task faulted: { task . Exception } ") ;
151+ throw task . Exception ;
152+ } , TaskContinuationOptions . OnlyOnFaulted ) ;
127153 }
128154
129155 /// <summary>
0 commit comments