title: Reliably counting the number of client connections to a SignalR hub
body: <p>I'm creating a web dashboard that will display the status of our test environments.</p>
  
  <p>I use a hub to connect the browser to the server and have a background task that polls the status of the environment. I only want to perform this check if at least one client is connected.</p>
  
  <p>My hub looks a little like this:</p>
  
  <pre><code>public class StatusHub : Hub
  {
      private static int connectionCount = 0;
  
      public override Task OnConnected()
      {
          Interlocked.Increment(ref connectionCount);
          return base.OnConnected();
      }
  
      public override Task OnReconnected()
      {
          Interlocked.Increment(ref connectionCount);
          return base.OnReconnected();
      }
  
      public override Task OnDisconnected()
      {
          Interlocked.Decrement(ref connectionCount);
          return base.OnDisconnected();
      }
  
      // other useful stuff
  }
  </code></pre>
  
  <p>This mainly works but sometimes OnConnected is called but OnDisconnected is not.</p>
  
  <p>One specific case is if I open chrome and type the address of the page but don't actually navigate to it. It seems Chrome is pre-fetching the page and connecting, but never disconnecting. </p>
  
  <p>So two questions:</p>
  
  <ol>
  <li>Is this a good approach to counting connections (I'm never going to be running in a web farm environment)? </li>
  <li>Will these zombied connections from Chrome eventually timeout (I tried setting timeouts very low but still didn't get a disconnect)? </li>
  </ol>