I think I have an issue with SignalR / multithreading and UI refresh.But I can't figure out why, when I receive a message from my hub the UI list of messages isn't refreshing.
I'm using Blazor server.
Here is interesting part of my razor file:
@page "/chat"@rendermode InteractiveServer<ul> @foreach (var message in messages) {<li>@message</li> }</ul>Here is my code behind:
private readonly List<string> messages = []; protected override async Task OnInitializedAsync() { hubConnection = new HubConnectionBuilder() .WithUrl(NavigationManager.ToAbsoluteUri("WHATEVER"), options => { options.AccessTokenProvider = async () => Task.FromResult("MYTOKEN") }) .Build(); hubConnection.On<string, string>("ReceiveMessageAsync", ReceivedNewMessage); await hubConnection.StartAsync(); } private async Task ReceivedNewMessage(string username, string message) { var encodedMsg = $"{username}: {message}"; messages.Add(encodedMsg); await InvokeAsync(StateHasChanged); }Looks like await InvokeAsync(StateHasChanged); isn't magically rendering again the list.
I've tried to peform the refresh of list with a simple button adding fake data. And it's working just fine. Funny fact when I do that in debugging, with two breakpoints, I'm not seeing the same content inside the list when I'm in the button refresh method and when I'm in the signalr refresh method. That's why I think about multithreading issue, and in particular issue when it's not a UI event.
I've seen similar issues on here, but no answers to my problem.
Here is my view in debug mode (I know the item is added to the list):
