Skip to content

A long running process in OnInitializedAsync causes the page load to increase accordingly in Blazor Server. Pls update guidance #59302

@mayur-ekbote

Description

@mayur-ekbote

If there is a long running process in OnInitializedAsync then the page load time increases by the amount of time it takes for the process to run.

Consider this:

@page  "/"

@if (isLoading)
{
    <div>Loading...</div>
}
else
{
    <div>Loaded</div>
}

@code {
    bool isLoading;

    protected override async Task OnInitializedAsync()
    {
            isLoading = true;
            await LoadDataAsync();
            isLoading = false;
    }

    private Task LoadDataAsync()
    {
        return Task.Delay(50_000);

    }
}

This page will take 50 seconds to load - i.e. the user will see nothing on the browser for 50 seconds. After that it will show the page with "Loading..." for 50 seconds before changing to "Loaded".

I assume that this is because Blazor Server renders the page twice - and the second pass starts only after first pass fully completes OnInitializedAsyc call.

But going by the guidance in the docs and the boilerplate "FetchData" example, this is the way to show "placeholder" for long running process.

The only thing that works as expected (immediate page load with "Loading..." message) is the following:

    protected override void OnInitialized()
    {
        Task.Run(async () => {
            await Task.Delay(50000);
            isLoading = false;
            await InvokeAsync(StateHasChanged);
        });
    }

However, this kind of defeats the purpose of OnInitializedAsyc.

Has this behaviour changed recently?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions