Search code examples
c#signalrsignalr-hubsignalr.client

Keeping connection alive in the right way from c# client


I have a self hosted signalr hub and two types of clients those connect to it.

  • Web apps: I can keep connection state as you see below using the disconnected event:

    $(function () {
        $.connection.hub.url = "http://localhost:8080/signalr";
    
        // Declare a proxy to reference the hub.
        var priceHub = $.connection.uTHub;
    
        $.connection.hub.start();
    
        $.connection.hub.disconnected(function () {
            setTimeout(function () {
                $.connection.hub.start();
            }, 2000); // Restart connection after 2 seconds.
        });
    });
    
  • Windows services:

        hubConnection = new HubConnection("http://localhost:8080/signalr", "source=" + feed, useDefaultUrl: false);
        priceProxy = hubConnection.CreateHubProxy("UTHub");
        hubConnection.Start().Wait();
    

In windows services, how can I handle the disconnected event (Restarting connection after 2 seconds behaviour) as I used in web apps?

Thanks in advance,


Solution

  • This is what I need:

    http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-net-client#connectionlifetime

            hubConnection.Closed += () => {
                connected = false;
                while (!connected)
                {
                    System.Threading.Thread.Sleep(2000);
                    hubConnection = new HubConnection("http://localhost:8080/signalr", "source=" + feed, useDefaultUrl: false);
                    priceProxy = hubConnection.CreateHubProxy("UTHub");
                    hubConnection.Start().Wait();
                    connected = true;
                }
            };