3

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

gartenriese
  • 4,131
  • 6
  • 36
  • 60
  • Did you try multiple simultaneous clients or is this trace from just a single client? – Caius Jard Nov 29 '21 at 16:53
  • Which version of Asp.net core SignalR you are using? If you are using the Asp.net core 5.0 or 6.0, you could try to configure the [server MaximumParallelInvocationsPerClient](https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration?view=aspnetcore-5.0&tabs=dotnet#configure-server-options-1) option. Besides, if you are using the previous version, Hub methods from the same connection are invoked sequentially. If you want to support parallel processing, you could have your Hub method start a background process that calls a client method when it completes (using HubContext). – Zhi Lv Nov 30 '21 at 03:12
  • @Caius Jard: The log above is from a single client. When using multiple clients, the server is processing the calls in parallel. – gartenriese Nov 30 '21 at 07:18
  • @Zhi Lv: Thank you! Using MaximumParallelInvocationsPerClient worked. – gartenriese Nov 30 '21 at 07:38

1 Answers1

1

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);
gartenriese
  • 4,131
  • 6
  • 36
  • 60