【问题标题】:Asp.NetCore UserStore slow user retrieval from database contextAsp.Net Core User Store 从数据库上下文中检索缓慢的用户
【发布时间】:2021-01-11 17:28:31
【问题描述】:

我有一个奇怪的情况,我不明白。在测试我的 API 时,我注意到缓慢的 api 查询归结为从商店中检索用户(登录后)。

当我在 UserStore 中覆盖 FindByIdAsync 方法时,我可以看到从 DbContext 中检索用户时有 500 毫秒的延迟。

public override async Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken = default)
{
    cancellationToken.ThrowIfCancellationRequested();
    ThrowIfDisposed();

    if (!int.TryParse(userId, out int id))
    {
        return null;
    }

    // This takes 500+ ms
    return Context.User.FirstOrDefault(u => u.Id == id);
}

现在奇怪的是,当我在控制器中执行相同操作时,速度很快。

例如:

[HttpGet]
public async Task<IActionResult> Get()
{
    // This function will end up at the UserStore.FindByIdAsync (see above)
    // And takes 500+ ms
    User user = await signInManager.UserManager.GetUserAsync(this.User);

    // This however is fast... (just using a sample id)
    context.User.Where(u => u.Id == 1896);

    return Ok(await context.Session.Where(s => s.UserId == user.Id).ToListAsync());
}

我不明白这是为什么。我尝试交换这两个功能,看看它是热身还是什么。但事实并非如此..

我还查看了 UserStore 的源代码,那里的 Context 应该与 Controller 中的上下文相同

我在控制器中注入上下文:

public SessionController(SignInManager<User> signInManager, MyDbContext context)
{
    this.signInManager = signInManager;
    // This is the same context as in the UserStore since the context is also injected in the  UserStore
    this.context = context;
}

【问题讨论】:

    标签: asp.net-mvc asp.net-core entity-framework-core asp.net-identity


    【解决方案1】:

    在 await 调用中添加 ConfigureAwait(false) 用户用户 = 等待 signInManager.UserManager.GetUserAsync(this.User).ConfigureAwait(false); await context.Session.Where(s => s.UserId == user.Id).ToListAsync().ConfigureAwait(false)

    【讨论】:

    • 如果可能,添加解释为什么此代码有效。这将有助于问题发布者理解他们为什么应该使用它。
    • 感谢您的回答。我认为调用实际上并没有执行到数据库直到我执行.ToListAsync() 或.SingleAsync()。这就是为什么我没有看到延迟。此外,问题出在其他地方,因为我通过 ssh 端口转发连接到我的数据库。我相信这就是为什么它实际上那么慢。我被一个执行速度快而另一个不执行的事实误导了(因为我上面说过)
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多