skip to content

In a Blazor WebAssembly component or a .NET app, how do you use the SignalR .NET client, and how should the component clean it up?

level: middleimportance: should knowfreq 40%

answer

  1. Microsoft.AspNetCore.SignalR.Client package
  2. WithUrl(Navigation.ToAbsoluteUri(...))
  3. On<T> returns an IDisposable
  4. InvokeAsync(StateHasChanged) from handlers
  5. IAsyncDisposable and DisposeAsync

basics

~10 s

Reference Microsoft.AspNetCore.SignalR.Client, build with new HubConnectionBuilder().WithUrl(Navigation.ToAbsoluteUri("/ticker")).Build(), register On<T> handlers, then StartAsync. In a component, re-render with InvokeAsync(StateHasChanged) and implement IAsyncDisposable to DisposeAsync the connection.

solid answer

~30 s

The .NET client lives in the `Microsoft.AspNetCore.SignalR.Client` package; the same API serves a console kiosk, a desktop app and a Blazor WebAssembly component. I build it with `new HubConnectionBuilder().WithUrl(Navigation.ToAbsoluteUri("/ticker")).WithAutomaticReconnect().Build()`, register handlers with `connection.On<string, decimal>("PriceChanged", (symbol, price) => ...)`, which returns an `IDisposable` that unregisters it, and then `await StartAsync()`. Calls use `InvokeAsync<T>`, `SendAsync` and `StreamAsync<T>`. Unlike the JavaScript client, handler names are matched case-sensitively. In a component the handler updates fields and calls `InvokeAsync(StateHasChanged)` to re-render on the component's dispatcher; the component implements `IAsyncDisposable` and calls `DisposeAsync()` on the connection, otherwise every visit to the page leaves another open connection behind.

code

csharp · 14 lines
csharp
// .NET kiosk worker using the same client API
await using var connection = new HubConnectionBuilder()
    .WithUrl("https://ticker.example.com/ticker")
    .WithAutomaticReconnect()
    .Build();

using var sub = connection.On<string, decimal>("PriceChanged",
    (symbol, price) => board.Update(symbol, price));

connection.Reconnecting += error => { log.LogWarning(error, "Reconnecting"); return Task.CompletedTask; };
connection.Closed += error => { log.LogError(error, "Closed"); return Task.CompletedTask; };

await connection.StartAsync(stoppingToken);
await connection.InvokeAsync("Subscribe", new[] { "MSFT", "CNTSO" }, stoppingToken);

go deeper

for a junior

Recall the package name, the HubConnectionBuilder, WithUrl, On, StartAsync and InvokeAsync calls, and that the component must dispose the connection.

for a middle

Explain why handlers call InvokeAsync(StateHasChanged), what On's IDisposable is for, and where the .NET client differs from the JavaScript one.

for a senior

Make long-running .NET clients robust: first-start retry, a never-ending retry policy, logged reconnect events and no leaked connections per navigation.

for a principal

Choose whether pages share one connection per hub through a scoped service or open their own, trading isolation against connection count.

## The package and the builder The .NET client is the NuGet package **`Microsoft.AspNetCore.SignalR.Client`**. It runs anywhere .NET runs: a console or desktop kiosk app, a worker service, a test, or a **Blazor WebAssembly** component in the browser. The API mirrors the JavaScript one with .NET naming: | Concern | .NET client | |---|---| | build | `new HubConnectionBuilder().WithUrl(url).Build()` | | reconnect | `.WithAutomaticReconnect()`, optionally with `TimeSpan[]` or an `IRetryPolicy` | | receive | `connection.On<T1, ...>(name, handler)` returning `IDisposable`; `connection.Remove(name)` | | call | `InvokeAsync<T>`, `SendAsync`, `StreamAsync<T>` / `StreamAsChannelAsync<T>` | | lifecycle | `StartAsync`, `StopAsync`, `DisposeAsync`, `State`, `ConnectionId` | | events | `Reconnecting`, `Reconnected`, `Closed` (each a `Func<..., Task>`) | Two differences from the JavaScript client catch people out: - **Handler names are case-sensitive.** The .NET client stores handlers with an ordinal comparer, so `On("pricechanged")` does not receive `SendAsync("PriceChanged")`. - **`HubConnectionState` has no `Disconnecting` value**; it has `Disconnected`, `Connected`, `Connecting` and `Reconnecting`. ## A Blazor WebAssembly ticker widget In a component that runs interactively in the browser, the pattern is: build and start in `OnInitializedAsync`, update state from handlers, dispose on teardown. ```razor @implements IAsyncDisposable @inject NavigationManager Navigation <p>MSFT: @price</p> @code { private HubConnection? hubConnection; private decimal price; protected override async Task OnInitializedAsync() { hubConnection = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri("/ticker")) .WithAutomaticReconnect() .Build(); hubConnection.On<string, decimal>("PriceChanged", (symbol, value) => { price = value; InvokeAsync(StateHasChanged); }); await hubConnection.StartAsync(); } public async ValueTask DisposeAsync() { if (hubConnection is not null) await hubConnection.DisposeAsync(); } } ``` What each line is for: 1. **`Navigation.ToAbsoluteUri("/ticker")`** builds the hub URL from the app's base address, the way the Blazor docs do it. 2. **`On<string, decimal>`** binds the server's arguments by position and type. Registering before `StartAsync` means no early push is missed. 3. **`InvokeAsync(StateHasChanged)`**: the handler is called by the SignalR client, not by a Blazor event, so the component does not re-render by itself. `ComponentBase.InvokeAsync` runs the work on the component's dispatcher, then `StateHasChanged` schedules the render. 4. **`IAsyncDisposable`**: when the user navigates away, Blazor disposes the component. Without `DisposeAsync` on the connection, each visit leaves a live connection and a handler pointing at a dead component. When and how often lifecycle methods run, including under prerendering, is a Blazor lifecycle topic; the SignalR part is the build, register, start and dispose sequence above. ## The same client in a kiosk app A .NET kiosk in the lobby uses the identical calls, usually in a hosted worker. The differences are operational: it should retry the first `StartAsync` in a loop, use an `IRetryPolicy` that never gives up, and log `Reconnecting`, `Reconnected` and `Closed` so an unattended device can be diagnosed. ## Mistakes to avoid - Forgetting `DisposeAsync`, which leaks connections per navigation. - Calling `StateHasChanged()` directly from the handler, outside the component's dispatcher. - Registering `On` handlers after `StartAsync`. - Assuming the JavaScript client's case-insensitive handler names apply to the .NET client. - Creating one connection per widget on a page that could share one per hub.

  • What does the IDisposable returned by HubConnection.On give you that Remove(name) does not?
    Disposing it removes just that one handler registration. `Remove(methodName)` removes every handler registered for the name. A component that shares a connection with others should dispose its own subscription rather than call `Remove`, which would also silence the other components.
  • A Blazor WebAssembly ticker widget shows prices only after the user clicks something. What is missing?
    The handler updates the field but never asks Blazor to re-render. SignalR callbacks are not Blazor UI events, so the component must call `InvokeAsync(StateHasChanged)` from the handler. A click triggers a render that happens to show the latest value, which hides the bug.

  • The .NET SignalR client matches On handler names case-insensitively like the JavaScript one.
  • Blazor re-renders automatically when a SignalR handler changes a field.
  • The HubConnection is disposed with the component, so DisposeAsync is unnecessary.
  • The .NET client ships in the shared framework, so no package reference is needed.
  • HubConnectionState.Disconnecting tells a .NET client that StopAsync is in progress.