xartal
xartal

Reputation: 457

SignalR await in hub method for long time

Hi,

I have a Hub on my server (azure webroles) with the following method:

public async Task<bool> Listen()
{
    var userid = ...;
    var observer = new BlackBoxObserver(userid){
        OnObserver = async (x) => { await Clients.Caller.NewMessage(x);}
    };
    await Task.Delay(TimeSpan.FromMinutes(5));
    await observer.Stop();
    return true;
}

BlackBoxObserver is something unrelated to SignalR and calls OnObserver on specific events. In this sample the observer is stopped after 5 minutes and the hub method returns.

My question is if this is a valid approach regarding the use of Hubs? Is there a timeout that you have to respect regarding hub calls?

In this StackOverflow Question op states "A hub doesn't feel like the right place to do this. A hub should be treated like an MVC/Web Api controller? So a request comes in, hub handles it, request is finished. End of story.". And that a background worker may be a better idea.

So I guess I could let the client join a Sessiongroup when he calls the hubmethod and then call the observer from a backgroundthread and call the group as described as here (asp.net/...). Would that be a better approach?

However, the easier and in some context also cleaner way for me would be the awaiting for a longer time in the hub method but I'm not sure if that may brings some problems with it.

Thanks for any help!

Upvotes: 3

Views: 2237

Answers (1)

Robbert Draaisma
Robbert Draaisma

Reputation: 463

I think those timeouts are configurable, but your question seems to be more conceptual. The shown logic reminds me of a longpolling construction, the client sends a request to the server. Then the server waits until new information is available and then returns with the response to the client. This is exactly the sort of thing SignalR is trying to abstract away from you.

A better way would be to pass along the connectionId of the client who wants the information and use:

 var hub =GlobalHost.ConnectionManager.GetHubContext("yourhubname");
 var client = hub.Clients.Client(connectionid);

to get a hub context and call the client back when you need/want to

Upvotes: 1

Related Questions