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.
Example. This page specifies the StreamRendering attribute. When it is first loaded, the "result" field in the code block is an empty string.
And The page will first render the "No result yet" message as the result field is empty.
However When the page is rendered, the OnInitializedAsync method is run. And this method runs a long-running task and sets the result field.
Finally Blazor renders the page again when the result field is set, so the page then prints the "Total size" message.
@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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.