Правильная логика для повторного подключения в SignalR с HubConnection

Мне нужно повторно подключить клиентское приложение (SignalR) к серверному приложению (SignalR), пока оно не будет подключено.

Но это ConnectionState.Reconnecting всегда ... Так что я понятия не имею, как переподключиться.

Я нашел этот подход Лучшая практика для повторного подключения SignalR 2.0 .NET клиент-серверный концентратор, говоря, что мы должны воссоздать HubConnection как уникальный рабочий подход ...

Есть подсказка?

У меня есть код

System.Timers.Timer connectionChecker = new System.Timers.Timer(20000);
HubConnection Connection { get; set; }

private void  ConnectionChecker_ElapsedAsync(object sender, System.Timers.ElapsedEventArgs e)
{
    if (Connection.State == ConnectionState.Disconnected)
    {
        connectionChecker.Stop();
        ForceConnectAsync().Start(); // In this method await Connection.Start();
    }
    else if (Connection.State == ConnectionState.Connecting)
    {
        // After conection lost it keeps this state ALWAYS.
        // But once server is up it still has this state.
    }
    else if (Connection.State == ConnectionState.Reconnecting)
    {
    }
    else if (Connection.State == ConnectionState.Connected)
    {
    }
}

person DmitryBoyko    schedule 20.10.2017    source источник
comment


Ответы (1)


Итак, я нашел это самое крутое решение Лучшая практика для переподключения клиента SignalR 2.0 .NET к серверному концентратору

private async Task<bool> ConnectToSignalRServer()
{
    bool connected = false;
    try
    {
        Connection = new HubConnection("server url");
        Hub = Connection.CreateHubProxy("MyHub");
        await Connection.Start();

        //See @Oran Dennison's comment on @KingOfHypocrites's answer
        if (Connection.State == ConnectionState.Connected)
        {
            connected = true;
            Connection.Closed += Connection_Closed;
        }
        return connected;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error");
        return false;
    }
}

private async void Connection_Closed()
{
    if(!IsFormClosed) // A global variable being set in "Form_closing" event of Form, check if form not closed explicitly to prevent a possible deadlock.
    {
        // specify a retry duration
        TimeSpan retryDuration = TimeSpan.FromSeconds(30);

        while (DateTime.UtcNow < DateTime.UtcNow.Add(retryDuration))
        {
            bool connected = await ConnectToSignalRServer(UserId);
            if (connected)
                return;
        }
        Console.WriteLine("Connection closed")
    }
}
person DmitryBoyko    schedule 20.10.2017