SignalR .Net Client: how to re-establish a connection

phoenix picture phoenix · Jul 3, 2013 · Viewed 12k times · Source

I have read this post

In some applications you might want to automatically re-establish a connection after it has been lost and the attempt to reconnect has timed out. To do that, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients). You might want to wait a period of time before calling Start in order to avoid doing this too frequently when the server or the physical connection are unavailable. The following code sample is for a JavaScript client using the generated proxy.

When I call the Start method from the Closed event

connection.Closed += connection_Closed;
static void connection_Closed()
    {
        Console.WriteLine("connection closed");
        ServerConnection.Start().Wait();
    }

Exception happened: the connection has not been established.

I want it continues until it success when the server is ok. Don't throw exception. How do I reach this.

any ideas?

thanks

Answer

phoenix picture phoenix · Oct 11, 2014

on .net client, you can call start method from closed event handler. if the server is unavailable, you should make a recursive call.

e.g.

_connection.Closed += OnDisconnected;
static void OnDisconnected()
{
    Console.WriteLine("connection closed");
    var t=_connection.Start()

    bool result =false;
    t.ContinueWith(task=>
    {
       if(!task.IsFaulted)
       {
           result = true;
       }
    }).Wait();

    if(!result)
    {
         OnDisconnected();
    }
}