Skip to content

Instantly share code, notes, and snippets.

@halter73
Last active August 20, 2019 20:59
Show Gist options
  • Save halter73/ccd66e2f7f819b37b960987f63bd6a0c to your computer and use it in GitHub Desktop.
Save halter73/ccd66e2f7f819b37b960987f63bd6a0c to your computer and use it in GitHub Desktop.
public class ReconnectSample
{
private readonly HubConnection _hubConnection;
private Task _runTask;
private TaskCompletionSource<object> _startTcs;
private volatile bool _stopping;
public Task StartAsync()
{
_startTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
_runTask = RunAsync();
return _startTcs.Task;
}
public Task StopAsync()
{
_stopping = true;
_hubConnection.Stop();
return _runTask;
}
public void ForceReconnect()
{
_hubConnection.Stop();
}
private async Task Run()
{
while (!_stopping)
{
var closeTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
Action closedHandler = () => closeTcs.SetResult(null);
try
{
_hubConnection.Closed += closedHandler;
await _hubConnection.Start();
// The below line could race with the client transitioning to the reconnecting state.
//Debug.Assert(_hubConnection.State == ConnectionState.Connected);
_startTcs.TrySetResult(null);
// The client might auto-reconnect during this time.
Console.WriteLine("Waiting for connection disconnect...");
await closeTcs.Task;
}
catch (Exception ex)
{
Console.WriteLine("ConnectionError='{0}'", ex);
// Consider varying the delay here so the clients don't flood the network all at once
// given a wide network outage. We also want to throttle the reconnect attempts in general.
await Task.Delay(TimeSpan.FromSeconds(5));
}
finally
{
Console.WriteLine("Connection disconnected.");
Debug.Assert(_hubConnection.State == ConnectionState.Disconnected);
_hubConnection.Closed -= closedHandler;
}
}
Console.WriteLine("Connection stopped...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment