DataLoading 保持 True

问题描述 投票:0回答:1

我正在使用下面的代码。用于更新 BL 和服务记录的表格。

Debtor
返回到 razor.cs(我可以在调试中看到它),但 DataLoading 保持 true。所以表格没有显示。有人有什么建议吗?

AddUpdate.razor.cs:

protected async override void OnInitialized()
{
    if (DataLoading)
    {
        return;
    }
    try
    {
        DataLoading = true;
        _debtor = await debtorBL.GetByIdAsync(DebtorId);
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        DataLoading = false;
    }
}

债务人BL.razor:

private readonly IDebtorService _debtorService;

public DebtorBL (IDebtorService debtorService)
{
    _debtorService = debtorService;
}

public async Task<Debtor> GetByIdAsync(int Id)
{
    return await _debtorService.GetByIdAsync(Id);
}

IDebtorService.cs:

public interface IDebtorService
{
    Task<bool> AddUpdateAsync(Debtor debtor);
    Task<bool> DeleteAsync(int Id);
    Task<Debtor> GetByIdAsync(int Id);
    Task<List<Debtor>> GetAllAsync();
}

DebtorService.cs:

public class DebtorService : IDebtorService
{
    private readonly IDbContextFactory<ApplicationDbContext> _factory;

    public DebtorService(IDbContextFactory<ApplicationDbContext> factory)
    {
        _factory = factory;
    }

    public async Task<Debtor> GetByIdAsync(int Id)
    {
        using (var _db = _factory.CreateDbContext())
        {
            return await _db.Debtors.SingleAsync(x => x.Id == Id);
        }
    }
}

没有看到问题所在。有什么建议吗?

c# entity-framework entity-framework-core blazor blazor-server-side
1个回答
1
投票

你正在做 NONO

async void

protected async override void OnInitialized()

这是一个同步方法。调用者没有等待的

Task
,因此组件生命周期方法会在等待完成之前运行完成。

_debtor = new();

之所以有效,是因为它是同步代码:没有屈服。

使用

OnInitializedAsync
版本。

protected async override Task OnInitializedAsync()
© www.soinside.com 2019 - 2024. All rights reserved.