Send concurrent SignalR messages with one connection

Viewed 360

How can I send multple SignalR messages in parallel with only one connection?

I have the following hub method:

public async Task Test()  
{  
    Console.WriteLine($"Start: {DateTime.Now}");  
    await Task.Run(() => Task.Delay(1000));  
    Console.WriteLine($"Stop: {DateTime.Now}");  
} 

In my client I have the following connection:

private connection: HubConnection = new HubConnectionBuilder()
  .withUrl(this.url)
  .configureLogging(LogLevel.Information)
  .withAutomaticReconnect([1000, 2000, 3000, 4000, 5000])
  .build();

I'm calling the hub method like this:

async test(): Promise<void> {
  try {
    console.log('start: ' + new Date().toString());
    await this.connection.invoke('Test');
    console.log('stop: ' + new Date().toString());
  } catch (err) {
    console.error(err);
  }
}

When I call the test method in my client multiple times, the hub is receiving the messages one after the other instead of all at once.

Client log:

start: Mon Nov 29 2021 17:27:35 GMT+0100 (3)
stop: Mon Nov 29 2021 17:27:36 GMT+0100
stop: Mon Nov 29 2021 17:27:37 GMT+0100
stop: Mon Nov 29 2021 17:27:38 GMT+0100

Server log:

Start: 29.11.2021 17:27:35
Stop: 29.11.2021 17:27:36
Start: 29.11.2021 17:27:36
Stop: 29.11.2021 17:27:37
Start: 29.11.2021 17:27:37
Stop: 29.11.2021 17:27:38

1 Answers

In order to allow multiple parallel invocations per client, you need to set the MaximumParallelInvocationsPerClient property, like this:

builder.Services.AddSignalR(options => options.MaximumParallelInvocationsPerClient = 10);
Related