Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this SignalR messages being received multiple times?

I am using SignalR in a Blazor server-side app. I added the Microsoft.AspNetCore.SignalR.Client Nuget package (v5.0.11) to the project, and used the following code to create the hub connection...

HubConnection hubConnection = new HubConnectionBuilder()
  .WithUrl("url")
  .Build();
await hubConnection.StartAsync();

I then send out a message with the following code (Debug.WriteLine added to confirm what's going on)...

Debug.WriteLine($"{DateTime.Now.ToLongTimeString()} SignalR msg sent");
await hubConnection.SendAsync("Send", "Hello");

The component that is to handle such messages creates the hub connection and hooks up to the On handler as follows...

HubConnection hubConnection = new HubConnectionBuilder()
  .WithUrl("url")
  .Build();
hubConnection.On<string>("Receive", msg =>
  Debug.WriteLine($"{DateTime.Now.ToLongTimeString()} SignalR msg received - {msg}"));
await hubConnection.StartAsync();

When the message is sent out, it is definitely only being sent once (which I can confirm from the output panel, where I only see the "sent" output once), but it is received twice.

Searching around, it seems that a common reason for this is if jQuery was loaded twice. However, I have checked this, and it's not the case. It's only being loaded the once. Furthermore, one of the other developers on the team tried it, and he got the message received 15 times! Even if we had accidentally included jQuery twice, we certainly didn't include it 15 times. Also, he's using exactly the same code as me (checked out from source control), so we should get the same results if this were the issue.

Anyone any idea why this could be happening? Thanks

like image 398
Avrohom Yisroel Avatar asked Oct 23 '25 07:10

Avrohom Yisroel


1 Answers

This can occur when you initialise a HubConnection within a component and don’t configure IDispose or IAsyncDispose on your component to dispose the HubConnection.

like image 123
Brian Parker Avatar answered Oct 24 '25 22:10

Brian Parker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!