How to send an event to a client when a client connects

32 Views Asked by At

I would like to send data to a client immediately after that client connects.

You can override OnConnectedAsync to do things when the client connects. Neat.

But it seems you cannot call any events on the client before that method has fully run.

So the best workaround I've found so far is to do something like this:

public override async Task OnConnectedAsync()
{
    var connectionId = Context.ConnectionId;
    
    [... putting the client in a list, whatever ...]

    // Send something "soon"
    _ = Task.Delay(TimeSpan.FromSeconds(0.5)).ContinueWith(task => SendInitialData(connectionId));
}

(my own code is threadsafe and does the sending via some singleton service+HubContext)

But this is quite a hack and is not actually guaranteed to work always.

Alternatively, one can create a method for the client to call (like Register()) that will send initial data as its return value. I'm trying to avoid that.

Is there a clean/recommended way to send a client event immediately on connecting? Is there a reason this functionality is missing?

I am not using Scaleout, only a single server instance that never recycles.

0

There are 0 best solutions below