我正在使用 .NET 6 構建 Blazor Server 應用程式。例如,我有一個客戶串列,我使用 Entityframework Core 從 Sqlite 資料庫中檢索這些客戶。我想在仍在檢索資料時顯示加載指示器。像這樣:
@page "/customers"
@inject CustomerService CustomerService
@if(customers.Count == 0)
{
<p>Loading...</p>
}
else
{
<table>
@foreach(Customer customer in customers)
{
<tr>
<td>
@customer.Id
</td>
<td>
@customer.Name
</td>
</tr>
}
</table>
}
當我使用以下資料實作時,它作業正常:
private List<Customer> customers = new();
protected async override Task OnInitializedAsync()
{
await Task.Run(() =>
{
this.customers = CustomerService.GetCustomers();
});
}
但是,當我使用以下資料實作時,它不起作用。這意味著整個頁面僅在資料加載后才可見(等待時的白頁)。
private List<Customer> customers = new();
protected async override Task OnInitializedAsync()
{
this.customers = await CustomerService.GetCustomersAsync();
}
客戶服務.cs
public class CustomerService
{
private CustomerContext _customerContext;
public CustomerService(CustomerContext customerContext)
{
_customerContext = customerContext;
}
public async Task<List<Customer>> GetCustomersAsync()
{
return await _customerContext.Customers.ToListAsync();
}
public List<Customer> GetCustomers()
{
return _customerContext.Customers.ToList();
}
}
我希望我的第二個實作也能異步作業。請問有人可以幫我理解嗎?我在這里錯過了什么?在此先感謝您的幫助!
uj5u.com熱心網友回復:
如果ToListAsync()真的/總是異步,這取決于您的資料庫。它可能會同步執行,具體取決于提供者、快取等。
有一個簡單的修復:
private List<Customer> customers = new();
protected async override Task OnInitializedAsync()
{
await Task.Delay(1);
this.customers = await CustomerService.GetCustomersAsync();
}
async Delay() 允許顯示 loading... 訊息。
請注意,您也可以在GetCustomers()沒有 Task.Run() 的情況下呼叫。
...來自 Sqlite 資料庫
這是關于 sqlite的答案,它實際上不支持異步操作。EF 提供者只是假裝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/394253.html
標籤:sqlite 实体框架核心 西装外套 blazor 服务器端
