doghappy / socket.io-client-csharp

socket.io-client implemention for .NET
MIT License
729 stars 125 forks source link

Unhandled TaskCanceledException #265

Closed johnyburd closed 2 years ago

johnyburd commented 2 years ago

My app is running in an environment where the network connection is somewhat unstable. When my machine disconnects from the network, the library (intermittently) raises this unhandled exception:

6.0.0 Description: The process was terminated due to an unhandled exception. 
Exception Info: System.Threading.Tasks.TaskCanceledException: A task was 
canceled. at 
System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken 
cancellationToken) at 
System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage 
request, Boolean async, CancellationToken cancellationToken) at 
System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage 
request, Boolean async, Boolean doRequestAuth, CancellationToken 
cancellationToken) at 
System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean 
async, CancellationToken cancellationToken) at 
System.Net.WebSockets.WebSocketHandle.ConnectAsync(Uri uri, CancellationToken 
cancellationToken, ClientWebSocketOptions options) at 
System.Net.WebSockets.ClientWebSocket.ConnectAsyncCore(Uri uri, 
CancellationToken cancellationToken) at 
SocketIOClient.Transport.DefaultClientWebSocket.ConnectAsync(Uri uri, 
CancellationToken cancellationToken) at 
SocketIOClient.Transport.WebSocketTransport.ConnectAsync(Uri uri) at 
SocketIOClient.Routers.WebSocketRouter.ConnectAsync() at 
SocketIOClient.SocketIO.ConnectAsync() at SocketIOClient.SocketIO.ConnectAsync() 
at SocketIOClient.SocketIO.InvokeDisconnect(String reason) at 
System.Threading.Tasks.Task.<>c.<ThrowAsync>b__127_1(Object state) 
at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute() at 
System.Threading.ThreadPoolWorkQueue.Dispatch() at 
System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart() at 
System.Threading.Thread.StartCallback() 

I'm on version 3.0.5.

I see the readme has some info on how to handle these exceptions in Xamarin, but I'm running a dotnet 6 service worker.

doghappy commented 2 years ago

When establishing a connection, the library will throw an exception if the network is unavailable. On different platforms, the exception type will be different.

Therefore, if the library cannot connect to the server, causing this exception, you should do this to ensure that the library can reconnect.

var client = new SocketIO("http://localhost:11000/“);
// ...
client.AddExpectedException(typeof(XxxException));
// ...

just like xamarin

johnyburd commented 2 years ago

When I was looking through the README I thought AddExpectedException was a Xamarin utility. I see now, thank you.