Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 4e2088d

Browse files
committed
Allow OperationCanceledExceptions to propagate out of ClientWebSocket.ConnectAsync
They're currently being wrapped in WebSocketExceptions, but they should be allowed to escape unwrapped.
1 parent c851f47 commit 4e2088d

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken,
223223
Abort();
224224
response?.Dispose();
225225

226-
if (exc is WebSocketException)
226+
if (exc is WebSocketException || exc is OperationCanceledException)
227227
{
228228
throw;
229229
}

src/System.Net.WebSockets.Client/tests/ConnectTest.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,5 +267,43 @@ public async Task ConnectAndCloseAsync_UseProxyServer_ExpectedClosedState(Uri se
267267
Assert.Equal(expectedCloseStatusDescription, cws.CloseStatusDescription);
268268
}
269269
}
270+
271+
[ConditionalFact(nameof(WebSocketsSupported))]
272+
public async Task ConnectAsync_CancellationRequestedBeforeConnect_ThrowsOperationCanceledException()
273+
{
274+
using (var clientSocket = new ClientWebSocket())
275+
{
276+
var cts = new CancellationTokenSource();
277+
cts.Cancel();
278+
Task t = clientSocket.ConnectAsync(new Uri("ws://" + Guid.NewGuid().ToString("N")), cts.Token);
279+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
280+
}
281+
}
282+
283+
[ConditionalFact(nameof(WebSocketsSupported))]
284+
public async Task ConnectAsync_CancellationRequestedAfterConnect_ThrowsOperationCanceledException()
285+
{
286+
var releaseServer = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
287+
await LoopbackServer.CreateClientAndServerAsync(async uri =>
288+
{
289+
var clientSocket = new ClientWebSocket();
290+
try
291+
{
292+
var cts = new CancellationTokenSource();
293+
Task t = clientSocket.ConnectAsync(uri, cts.Token);
294+
Assert.False(t.IsCompleted);
295+
cts.Cancel();
296+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
297+
}
298+
finally
299+
{
300+
releaseServer.SetResult(true);
301+
clientSocket.Dispose();
302+
}
303+
}, server => server.AcceptConnectionAsync(async connection =>
304+
{
305+
await releaseServer.Task;
306+
}), new LoopbackServer.Options { WebSocketEndpoint = true });
307+
}
270308
}
271309
}

0 commit comments

Comments
 (0)