为什么SaveChangesAsync实际上没有保存我的所有更改?

Pau*_*ski 4 .net c# task-parallel-library async-await entity-framework-6

我想我可能会错过一些关于这应该如何工作的东西.我有一些导入文件的代码.它循环遍历每条记录,进行一些处理,然后通过DbContext实例将该记录添加到表中.

我初始化DbContext如下:

protected void ResetDbContext()
{
    if (_db != null)
        _db.Dispose();

    _db = new AppDBEntities();
    _db.Configuration.AutoDetectChangesEnabled = false;
    _db.Configuration.ValidateOnSaveEnabled = false;
}
Run Code Online (Sandbox Code Playgroud)

我的主循环看起来像这样:

foreach (var rec in engine)
{
    var record = new CommonImportRecord(rec);
    ProcessRecord(record, options, index);
    index++;
}

_db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

ProcessRecord 看起来像这样:

protected async Task<int> ProcessRecord(CommonImportRecord record, ImportOptions options, int index)
{
    DisplayProcessStatus(index, options);
    // Code removed which fills in various properties of the record
    _db.MyTable.Add(record);
    if (index % options.UpdateInterval == 0)
    {
        return await _db.SaveChangesAsync();
        // This was originally here, commented out when I changed SaveChanges() to SaveChangesAsync()
        // ResetDBContext();
    }
}
Run Code Online (Sandbox Code Playgroud)

我做的唯一真正的改变SaveChangesAsync()是添加async Task<int>作为返回类型ProcessRecord,更改SaveChanges()return await SaveChangesAsync()和注释掉调用ResetDBContext.

在异步更改之前,事情按预期工作.之后,似乎没有保存我的所有记录.

我在这里错过了什么?

i3a*_*non 11

您正在调用一个async方法,该方法返回任务而无需等待它完成.您需要使用await异步上移动到下一个记录之前等待.async使用"Async"后缀命名方法也是一个标准:

foreach (var rec in engine)
{
    var record = new CommonImportRecord(rec);
    var result = await ProcessRecordAsync(record, options, index);
    index++;
}
Run Code Online (Sandbox Code Playgroud)