Blazor 服务器:"System.InvalidOperationException: A second operation was started on this context before a previous operation completed"

Blazor Server: "System.InvalidOperationException: A second operation was started on this context before a previous operation completed"

我的 blazor 页面中有以下 OnAfterRenderAsync 函数:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    try
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("initializeDropZone");

            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;


            if (user.Identity.IsAuthenticated)
            {
                var userSecurityInfo = await UserManager.GetUserAsync(user);
                var userDbImages = (await ImageData.GetImagesByUser(userSecurityInfo.Id)).ToList();
                foreach (var dbImage in userDbImages)
                {
                    _userFiles.Add(new ImageModel()
                    {
                        ID = dbImage.ID,
                        DatasetName = dbImage.DatasetName,
                        Name = dbImage.FileName,
                        UploadDate = dbImage.UploadDate,
                        BucketUrl = dbImage.BucketUrl,
                        BucketUrlExpireDate = dbImage.BuckeUrlExpireDate
                    });
                }
            }
            StateHasChanged();
        }
    }
    catch(Exception e)
    {
        Console.WriteLine("OnAfterRenderError (DataManagement):" + e.Message);
    }
    await base.OnAfterRenderAsync(firstRender);

    return;
}

虽然通常此操作非常快(它仅加载图像 URL 而不是实际图像数据),但在服务器首次启动后需要一些时间。如果用户决定在操作仍在 运行 时更改页面,我会收到以下错误:

fail: Microsoft.EntityFrameworkCore.Query[10100] An exception occurred while iterating over the results of a query for context type 'WebApplication.Data.ApplicationDbContext'. 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. at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync() 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. at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync()

如有任何关于如何解决此问题并更好地理解问题的建议,我们将不胜感激。到目前为止,我只是捕获异常,因此应用程序不会崩溃,但我想首先阻止它。

我的猜测是这一行:

var userDbImages = (await ImageData.GetImagesByUser(userSecurityInfo.Id)).ToList();
当您更改页面时,

仍在 DbContext 上执行,因此无论在新页面上进行什么数据库调用,它都会失败,因为唯一的 DbContext 已在使用中。我猜是因为此时我不知道 ImageData 是什么!

DbContext 工厂解决了这些问题,因此您需要解决实施工厂时遇到的问题,因为您无法 运行 在实际应用程序中针对单个上下文进行异步数据库操作。 Post 关于工厂问题的问题,我们会看看是否可以提供帮助。

关于设计的进一步评论:使用范围视图服务来保存图像数据,因此您只获得一次:如果我读错了这段代码而您已经在 ImageData 中读错了,请忽略。