簡體   English   中英

異步方法:在上一個操作完成之前,在此上下文上啟動了第二個操作

[英]Async method: Second operation was started on this context before a previous operation completed

我是 Blazor 的新手,沒有太多使用 Tasks 的經驗,所以希望我只是犯了一個愚蠢的錯誤。 我有一個通過按鈕按下調用的異步方法,但如果在 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.

為用戶表中的每一行呈現此按鈕。 我正在嘗試快速連續刪除多個用戶記錄,但收到上述錯誤。

這是按鈕按下的代碼(使用 AntBlazor)

 <Button Type="primary" Danger OnClick="@(async() => await RemoveAsync(user))">Remove User</Button>

這是 RemoveAsync 方法的代碼。

private async Task RemoveAsync(User user)
{
   await UserService.UpdateUserAsync(user);
}

我誤解了 async/await 的工作原理嗎? 或者我是否需要使用任務來確保操作完成?

編輯:

繼承人 UserService.UpdateUserAsync() 代碼

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

你的代碼

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

我假設 _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
}

現在上下文的范圍是每個方法。 內存更輕,您可以進行許多重疊操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM