我有个问题。我有 ASP .NET Core REST API 应用程序,并且在一种方法中,我试图将更多更改异步写入数据库。每次将不同数量的对象写入数据库时,每次出现三种不同错误之一。任何建议可以是错的?
这是我的代码:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection_string), ServiceLifetime.Transient);
services.AddScoped<IHelper, Helper>();
...
}
助手.cs
private MyDbContext _dbContext;
public Helper(IOptions<HelperSettings> settings, ILogger<Helper> logger, MyDbContext dbContext)
{
...
_dbContext = dbContext;
...
}
public void Save(object entity)
{
...
_dbContext.Add(entity);
}
这是引发异常的控制器和方法。
public class MyController : ControllerBase
{
private readonly Helper _db;
public MyController(IHelper helper)
{
_db = helper;
}
...
[HttpPost]
[Route("something")]
[Produces("application/json")]
public async Task<ActionResult<Guid>> CreateSomethingAsync([FromBody] DataRequest data)
{
...
if (data.Answers != null)
{
List<Task> saveTasks = new List<Task>();
foreach (AnswerData ans in data.Answers)
{
Answer answer = ans.ConvertToAnswer(); //just create new Answer instance and filll it with data from AnswerData
saveTasks.Add(Task.Run(() => _db.Save(answer)));
}
await Task.WhenAll(saveTasks);
await _db.DbContext.SaveChangesAsync();
}
return Ok(...);
}
}
我CreateSomethingAsync()在另一个应用程序中循环调用。它抛出以下三个异常之一:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
或者
System.InvalidOperationException: 'Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.'
或者
System.InvalidOperationException: Cannot start tracking InternalEntityEntry for entity type 'Answer' because another InternalEntityEntry is already tracking the same entity
_dbContext.Add(entity);在我的线上Helper.cs。
我知道问题出在并行性上,但我不知道如何解决。有任何想法吗?