StreamRendering
Sometimes a Blazor page may not have all its data available when it is first rendered. With StreamRendering
, an attribute, we can specify that a "loading" message appears.
With the OnInitializedAsync
method, we can run a task when the page loads. Then, when it is finished, Blazor will automatically render the page with the final result.
This page specifies the StreamRendering
attribute. When it is first loaded, the "result" field in the code block is an empty string
.
OnInitializedAsync
method is run. And this method runs a long-running task and sets the result field.@page "/stream" @attribute [StreamRendering] @* If result is empty, print an initial message and wait for it to be set *@ @if (string.IsNullOrEmpty(result)) { <p>NO RESULT YET</p> } else { <p>TOTAL SIZE: @result</p> } @code { string result = ""; protected override async Task OnInitializedAsync() { // Run this method when the page is initialized. var count = await Task.Run(Test); // Store result in field. result = count.ToString(); } int Test() { // Compute something that takes some time. var total = 0; for (int i = 0; i < 100; i++) { var list = new List<int>(); for (int z = 0; z < 10000; z++) { list.Add(z); if (z >= 100) { list.Remove(0); } } total += list.Count; } return total; } }
For pages that require a loading message, and may have data that takes a while to fetch (as from a database or external source), StreamRendering
is a good choice. It allows for a loading message.