dotnet / dotnet/AspNetCore.Docs
Misleading and broken code example for "Manually reconnect" after SignalR connection closed
- Dominant language
- C#
- Stars
- 13.1k
- Forks
- 24.6k
- Avg merge
- 1d 3h
- Merged PRs (30d)
- 97
Description
### Description
The section "Manually reconnect" contains this example:
```csharp
connection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0,5) * 1000);
await connection.StartAsync();
};
```
However, I could not get this to work and I've spent an annoying amount of time double-checking I had followed the various steps in the setup.
As far as I can tell, this example code is broken and not reliable, because if the network or server is not back and accepting connections within a second or 2, *the call to `StartAsync()` will throw an exception, the connection attempt will be abandoned, and there will be no new call to the `Closed` handler, so no additional attempts will be made*:
```
System.Net.Http.HttpRequestException: Connection refused (localhost:7321)
---> System.Net.Sockets.SocketException (111): Connection refused
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
```
The code example does not show this and the surrounding text doesn't even hint about it. Quite the opposite, the current text in that section gives a clear impression that it is all you need to do.
I think the section should at least point this out.
For what it's worth, it seems calling the `ConnectWithRetryAsync()` method, provided earlier in the article, from the `Closed` event handler instead of directly calling `StartAsync()` makes it more robust.
### Page URL
https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-8.0&tabs=visual-studio
### Content source URL
https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/signalr/dotnet-client.md
### Document ID
36052173-7061-6d01-8aed-915685cd7cf6
### Article author
@bradygaster
Contributor guide
Assessment
This issue has not been assessed yet.