Couple of my API controllers need to have access to Hub Context and I know that the GlobalHost.ConnectionManager.GetHubContext call is expensive. Is there an efficient way to do that?
1 Answer
How do you know the GlobalHost.ConnectionManager.GetHubContext call is expensive?
I just tried calling GetHubContext 10,000 times in a loop and that took 174 milliseconds on my machine. That means each call averaged 0.0000174 seconds. I don't think that is particularly expensive in the context of most Web API calls or web request in general.
If the very first call to GetHubContext is made before any SignalR connections are established, then that the initial call will take longer. On my machine, this first call took 96 milliseconds. This time was spent initializing some SignalR singletons that would normally be initialized when the first SignalR connection is established. Subsequent calls averaged the .0174 milliseconds referenced above.
If that's too expensive, you can always store the returned IHubContext in a singleton. It's thread-safe.