CodexBloom - Programming Q&A Platform

Unhandled exception when using async-await in .NET 7 Blazor WebAssembly with SignalR

👀 Views: 62 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
blazor signalr async-await C#

I'm working on a personal project and I'm working on a Blazor WebAssembly application that uses SignalR for real-time communication. I've encountered an unhandled exception when trying to connect to a SignalR hub. The exception message reads: `System.InvalidOperationException: 'The 'HubConnection' must be started before calling methods on it.'` I have a method that initializes the connection and then calls a method on the hub after a delay, but it seems like the connection isn't fully established before the call is made. Here's a simplified version of my code: ```csharp @inject NavigationManager Navigation @inject IHubContext<MyHub> HubContext @code { private HubConnection _hubConnection; protected override async Task OnInitializedAsync() { _hubConnection = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri("/myhub")) .Build(); _hubConnection.On<string>("ReceiveMessage", (message) => { // Handle the incoming message }); await _hubConnection.StartAsync(); } private async Task SendMessage(string message) { // Wait for a few seconds before sending the message await Task.Delay(2000); await _hubConnection.InvokeAsync("SendMessage", message); } } ``` In the `SendMessage` method, it's possible for the method to be called before `_hubConnection` is fully started. I've tried checking if the connection is in the `HubConnectionState.Connected` state before calling `InvokeAsync`, but I still encounter the exception intermittently. I've also added error handling around the invocation call, but I would still like to know if there's a more robust way to ensure that the connection is fully established before making calls to the hub. Any suggestions? This is part of a larger CLI tool I'm building. Any help would be greatly appreciated! This is for a service running on Ubuntu 22.04. What are your experiences with this? This issue appeared after updating to C# 3.9. I'd love to hear your thoughts on this.