Hello Balaji Mogadali,
This is a threading issue with Blazor and SignalR integration. The problem occurs because SignalR events come in on a different thread than Blazor's UI thread, which can cause rendering issues.
Looking at your code, the main issue is in your HandleNotificationReceived method. Here are the key changes that should fix the rendering problem:
private Task HandleNotificationReceived(SignalRNotificationMessage notification)
{
return InvokeAsync(() =>
{
try
{
Console.WriteLine($"Received: {notification.Message}");
notifications.Add(notification);
Console.WriteLine($"Notification count: {notifications.Count}");
StateHasChanged(); // Move this inside InvokeAsync, remove the await
}
catch (Exception ex)
{
Console.WriteLine("Error in UI update: " + ex.Message);
}
});
}
The key changes:
- Remove the
asyncandawaitfrom inside theInvokeAsync- you don't need them here - Move
StateHasChanged()directly inside theInvokeAsyncwithout the extraawait InvokeAsync(StateHasChanged) - Remove the call to
OnAfterRenderAsync(true)- that's not needed for this scenario
Also, I noticed in your OnAfterRenderAsync method, you're calling StateHasChanged() again on first render. You can simplify that to:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Only do first-render specific tasks here if needed
// StateHasChanged() isn't necessary here
}
One more thing to check, make sure your SignalR connection is actually established before trying to update the UI. You might want to add a check like:
if (signalRNotificationService.ConnectionState == HubConnectionState.Connected)
{
// Your notification handling logic here
}
The threading context is really important with Blazor Server, SignalR events come in on a different thread, so InvokeAsync ensures your UI updates happen on the correct thread that Blazor's renderer expects.
Hope this helps!