异步方法:在上一个操作完成之前在此上下文上启动第二个操作

zzz*_*zzz 0 .net c# blazor blazor-server-side

我是 Blazor 的新手,没有太多使用任务的经验,所以希望我只是犯了一个愚蠢的错误。我有一个通过按下按钮调用的异步方法,但如果在 1-2 秒内再次调用该方法,我会收到以下异常。

Error: System.InvalidOperationException: A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
Run Code Online (Sandbox Code Playgroud)

此按钮针对“用户”表中的每一行呈现。我试图快速连续删除多个用户记录,但收到上述错误。

这是按下按钮的代码(使用 AntBlazor)

 <Button Type="primary" Danger OnClick="@(async() => await RemoveAsync(user))">Remove User</Button>
Run Code Online (Sandbox Code Playgroud)

这是RemoveAsync 方法的代码。

private async Task RemoveAsync(User user)
{
   await UserService.UpdateUserAsync(user);
}
Run Code Online (Sandbox Code Playgroud)

我是否误解了 async/await 的工作原理?或者我是否需要利用任务来确保操作完成?

编辑:

这是 UserService.UpdateUserAsync() 代码

public async Task<bool> UpdateUserAsync(User user)
{
   _appDBContext.Users.Update(user);
   await _appDBContext.SaveChangesAsync();
   return true;
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 6

你的代码

public async Task<bool> UpdateUserAsync(User user)
{
   _appDBContext.Users.Update(user);
   await _appDBContext.SaveChangesAsync();
   return true;
}
Run Code Online (Sandbox Code Playgroud)

我假设 _appDBContext 被注入到构造函数中,并且 UserService 本身已注册为 Scoped。

这意味着单个 _appDBContext 在表单的持续时间内存在,积累跟踪数据。因为async它存在被重新输入的风险,这是你的直接问题。

一种解决方案是不注入 DbContext而是注入 DbContextFactory

然后它看起来像:

public async Task<bool> UpdateUserAsync(User user)
{
   using var dbContext = _dbContextFactory.CreateDbContext(); 
   dBContext.Users.Update(user);
   var n = await dBContext.SaveChangesAsync();
   return n == 1; // just for being accurate
}
Run Code Online (Sandbox Code Playgroud)

现在上下文的范围仅限于每个方法。占用的内存要少得多,并且您可以进行许多重叠的操作。