为什么我的 Blazor Server 应用程序在检索数据之前一直等待呈现,即使在使用异步时也是如此?

Why is my Blazor Server App waiting to render until data has been retrieved, even when using async?

我正在使用 .NET 6 构建 Blazor 服务器应用程序。 例如,我有一个使用 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();
}

CustomerService.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();
        }
    }

我希望我的第二个实现也能异步工作。谁能帮我理解一下吗?我在这里错过了什么?在此先感谢您的帮助!

这取决于您的数据库 ToListAsync() 是否真的并且总是异步的。它可能会同步执行,具体取决于提供程序、缓存等。

有一个简单的修复方法:

private List<Customer> customers = new();

protected async override Task OnInitializedAsync()
{
   await Task.Delay(1);
   this.customers = await CustomerService.GetCustomersAsync();
}

async Delay() 将允许显示正在加载...消息。

请注意,您应该在不使用 Task.Run() 的情况下调用 GetCustomers()

... from a Sqlite db

关于sqlite..它实际上不支持异步操作。 EF 提供者只是假装。