Aside

Blazor Server Tip: Sometimes you need Task.Delay(1)

I recently encountered an issue with server-side Blazor in which the UI didn’t refresh after calling StateHasChanged. The UI refreshed just fine until I added about 30k more records to a database table, which caused a query to take a bit longer to run. I filed an issue here.

I debugged through the issue by trying different things like using an in-memory data store, re-checking against a smaller data set, and wrapping StateHasChanged to make sure it was actually called. Everything was working as expected with the in-memory store and smaller data set, and StateHasChanged was always called. However, with the larger data set, the components’ lifecycle methods were not called.

I finally stumbled upon a solution using an old JavaScript trick: adding await Task.Delay(1); This magically worked. If you run into something similar, you may try await Task.Delay(1); and see whether that resolves the issue.

Advertisement