SignalR Connection Unexpectedly Closes in Blazor Server Application

I’m building a Blazor Server application that uses SignalR to push real-time sensor data from the server to the client. The client seems to be unable to receive data, and the connection is unexpectedly closed by the server. Application is published to raspberry pi 3b (arm64 architecture). Here is a summary of the problem and the relevant code:

info: Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[6]
      HttpConnection Disposed.
dbug: Microsoft.AspNetCore.SignalR.Client.HubConnection[46]
      Canceling all outstanding invocations.
dbug: Microsoft.AspNetCore.SignalR.Client.HubConnection[21]
      HubConnection stopped.
dbug: Microsoft.AspNetCore.SignalR.Client.HubConnection[51]
      Invoking the Closed event handler.
fail: WeatherStationBlazor.Components.Pages.Weather[0]
      Connection closed:
fail: Microsoft.AspNetCore.SignalR.Client.HubConnection[27]
      An exception was thrown in the handler for the Closed event.
      System.ObjectDisposedException: Cannot access a disposed object.
      Object name: 'Microsoft.AspNetCore.SignalR.Client.HubConnection'.

My Program.cs file with configuration

using Microsoft.AspNetCore.Http.Connections;
using WeatherStationBlazor.Components;
using WeatherStationBlazor.Data;

namespace WeatherStationBlazor
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddRazorComponents()
                .AddInteractiveServerComponents();
            builder.Services.AddHostedService<SensorDataBackgroundService>();
            builder.Services.AddSingleton<Bme280Service>();
            builder.Services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
                hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
            });

            builder.WebHost.ConfigureKestrel(options =>
            {
                options.ListenAnyIP(5000);
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAntiforgery();

            app.MapRazorComponents<App>()
                .AddInteractiveServerRenderMode();
            app.MapHub<SensorHub>("/sensorHub", options =>
            {
                options.Transports =
                    HttpTransportType.WebSockets |
                    HttpTransportType.LongPolling;
            });

            app.Run();
        }
    }
}

Client-Side Code (Blazor Component):
Here is the Blazor component that initializes the SignalR connection:

@page "/weather"
@using Microsoft.AspNetCore.SignalR.Client
@inject WeatherStationBlazor.Data.Bme280Service Bme280Service
@inject NavigationManager NavigationManager
@inject ILogger<Weather> Logger
@implements IAsyncDisposable

<h3>Real-Time Weather Data</h3>

@if (!dataLoaded)
{
    <p>Loading...</p>
}
else
{
    <p>Temperature: @temperature?.ToString("F2") °C</p>
    <p>Humidity: @humidity?.ToString("F2") %</p>
    <p>Pressure: @pressure?.ToString("F2") hPa</p>
}

@code {
    private double? temperature;
    private double? humidity;
    private double? pressure;
    private bool dataLoaded = false;

    private HubConnection? hubConnection;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            Logger.LogInformation("Initializing Hub connection...");
            hubConnection = new HubConnectionBuilder()
                .WithUrl(NavigationManager.ToAbsoluteUri("/sensorHub"))
                .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5) })
                .ConfigureLogging(logging =>
                {
                    logging.AddConsole();
                    logging.SetMinimumLevel(LogLevel.Debug);
                })
                .Build();

            hubConnection.Closed += async (error) =>
            {
                Logger.LogError($"Connection closed: {error?.Message}");
                await Reconnect();
            };

            hubConnection.On<double, double, double>("ReceiveSensorData", async (temp, hum, pres) =>
            {
                Logger.LogInformation($"Received data: Temperature: {temp}, Humidity: {hum}, Pressure: {pres}");
                temperature = temp;
                humidity = hum;
                pressure = pres;
                await InvokeAsync(StateHasChanged);
            });

            await StartHubConnectionAsync();

            // Load initial data
            Logger.LogInformation("Loading initial sensor data...");
            var data = await Bme280Service.ReadSensorDataAsync();
            temperature = data.temperature;
            humidity = data.humidity;
            pressure = data.pressure;
            dataLoaded = true;
        }
        catch (Exception ex)
        {
            Logger.LogError($"Error initializing Hub connection: {ex.Message}");
            dataLoaded = false;
        }
    }

    private async Task StartHubConnectionAsync()
    {
        if (hubConnection != null && hubConnection.State == HubConnectionState.Disconnected)
        {
            try
            {
                await hubConnection.StartAsync();
                Logger.LogInformation("Hub connection started successfully.");
            }
            catch (Exception ex)
            {
                Logger.LogError($"Error starting Hub connection: {ex.Message}");
                await Task.Delay(5000); // Wait for 5 seconds before retrying
                await StartHubConnectionAsync();
            }
        }
    }

    private async Task Reconnect()
    {
        Logger.LogInformation("Attempting to reconnect...");
        while (hubConnection?.State == HubConnectionState.Disconnected)
        {
            try
            {
                await hubConnection.StartAsync();
                Logger.LogInformation("Reconnected to Hub.");
                return;
            }
            catch (Exception ex)
            {
                Logger.LogError($"Reconnection attempt failed: {ex.Message}");
                await Task.Delay(2000); // Wait for 2 seconds before retrying
            }
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (hubConnection != null)
        {
            var connection = hubConnection;
            hubConnection = null;

            try
            {
                await connection.StopAsync();
                Logger.LogInformation("Hub connection stopped successfully.");
            }
            catch (Exception ex)
            {
                Logger.LogError($"Error stopping Hub connection: {ex.Message}");
            }
            finally
            {
                await connection.DisposeAsync();
                Logger.LogInformation("Hub connection disposed.");
            }
        }
    }
}
Setting up automatic reconnection using .WithAutomaticReconnect().
Adjusting KeepAliveInterval and ClientTimeoutInterval.
Ensuring the HubConnection is properly disposed when the component is destroyed.

Questions:

What could be causing the SignalR connection to be unexpectedly closed by the server?
How can I ensure that the client consistently receives data from the server without the connection being dropped?
Are there any specific configurations or patterns I should follow to improve the stability of the SignalR connection in a Blazor Server application?
Any help or insights would be greatly appreciated!

New contributor

kamillo122 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật