Best practice for reconnecting SignalR 2.0 .NET client to server hub

后端 未结 5 443
忘掉有多难
忘掉有多难 2020-12-04 06:06

I\'m using SignalR 2.0 with the .NET client in a mobile application which needs to handle various types of disconnects. Sometimes the SignalR client reconnects automatically

5条回答
  •  时光说笑
    2020-12-04 06:26

    Since the OP asking for a .NET client (a winform implementation below),

    private async Task 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;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        return connected;
    }
    
    private async void Connection_Closed()
    {   // A global variable being set in "Form_closing" event 
        // of Form, check if form not closed explicitly to prevent a possible deadlock.
        if(!IsFormClosed) 
        {
            // specify a retry duration
            TimeSpan retryDuration = TimeSpan.FromSeconds(30);
            DateTime retryTill = DateTime.UtcNow.Add(retryDuration);
    
            while (DateTime.UtcNow < retryTill)
            {
                bool connected = await ConnectToSignalRServer();
                if (connected)
                    return;
            }
            Console.WriteLine("Connection closed")
        }
    }
    

提交回复
热议问题