@@ -41,6 +41,8 @@ class TextWebSocketClient : IWebSocketClient
41
41
/// </summary>
42
42
public event EventHandler < string > MessageReceived ;
43
43
44
+ private readonly object connectionLock = new object ( ) ;
45
+
44
46
/// <summary>
45
47
/// Opens a WebSocket connection to the specified server URI and starts listening for messages.
46
48
/// If the connection is already open or in a connecting state, this method does nothing.
@@ -52,7 +54,10 @@ class TextWebSocketClient : IWebSocketClient
52
54
/// </returns>
53
55
public async Task OpenAsync ( string serverUri , CancellationToken cancellationToken = default )
54
56
{
55
- webSocket ??= new ClientWebSocket ( ) ;
57
+ lock ( connectionLock )
58
+ {
59
+ webSocket ??= new ClientWebSocket ( ) ;
60
+ }
56
61
57
62
if ( webSocket . State != WebSocketState . Open && webSocket . State != WebSocketState . Connecting )
58
63
{
@@ -92,14 +97,26 @@ private async Task ListenForMessages(CancellationToken cancellationToken)
92
97
}
93
98
94
99
string message = Encoding . UTF8 . GetString ( buffer , 0 , result . Count ) ;
100
+ Debug . WriteLine ( $ "Received message: { message } ") ;
95
101
MessageReceived ? . Invoke ( this , message ) ;
96
102
}
97
103
}
98
104
catch ( OperationCanceledException ex )
99
105
{
100
106
// 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 } ") ;
102
113
}
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" ) ;
103
120
}
104
121
105
122
/// <summary>
@@ -123,7 +140,16 @@ private void StartListening(CancellationToken cancellationToken)
123
140
}
124
141
125
142
await ListenForMessages ( cancellationToken ) ;
143
+ Debug . WriteLine ( "Websocket listeningTask stopped" ) ;
126
144
} , 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 ) ;
127
153
}
128
154
129
155
/// <summary>
0 commit comments