Home
C#.ASP.NET
StreamRendering Use (Blazor)
This page was last reviewed on Jan 4, 2024.
Dot Net Perls
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 4, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.