在Blazor 中的API 呼叫期間動態顯示使用者回饋
在Blazor 中,處理長時間運行的API 呼叫需要提供使用者回饋,例如顯示等待遊標或“旋轉”圖像。本文介紹了兩種實現此目的的方法:
選項 1:使用 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 }
選項 2:使用 Task.Run() (不適用於WebAssembly)
建立一個包含長操作的任務:
async Task AsyncLongOperation() // this is an async task { spinning=true; await Task.Run(()=> LongOperation()); //<--here! currentCount++; spinning=false; }
效果預渲染
在Blazor Server 應用程式中,由於預渲染,微調器可能不會顯示。若要解決此問題,請在 OnAfterRender 中執行長操作,而不是 OnInitializedAsync。
protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await Task.Run(()=> LongOperation());//<--or Task.Delay(0) without Task.Run StateHasChanged(); } }
更多關於有效旋轉器實現的見解,請探索開源專案 BlazorPro.Spinkit。
以上是如何在 Blazor 中長時間運行的 API 呼叫期間動態顯示使用者回饋?的詳細內容。更多資訊請關注PHP中文網其他相關文章!