Blazor enables you to display feedback to the user during long-running API calls using visual cues like wait cursors or spinner images.
Issue:
In your Blazor application, you attempted to use CSS to display a spinning cursor during API calls. However, the page content was not refreshed until the call was completed.
Option 1: Using Task.Delay(1)
private async Task AsyncLongFunc() // this is an async task { spinning=true; await Task.Delay(1); // flushing changes. The trick!! LongFunc(); // non-async code currentCount++; spinning=false; await Task.Delay(1); // changes are flushed again }
Option 2: Using Task.Run() (Not for WebAssembly)
async Task AsyncLongOperation() // this is an async task { spinning=true; await Task.Run(()=> LongOperation()); //<--here! currentCount++; spinning=false; }
Note for Server-Side Prerendering:
In Blazor Server apps, the spinner will not appear due to prerendering. To make it visible, perform the long operation in OnAfterRender.
protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await Task.Run(()=> LongOperation());//<--or Task.Delay(0) without Task.Run StateHasChanged(); } }
For more examples and information, refer to open source projects like BlazorPro.Spinkit.
The above is the detailed content of How to Display a Spinner During Long-Running API Calls in Blazor?. For more information, please follow other related articles on the PHP Chinese website!