Why isn't SaveChangesAsync actually saving all of my changes?

.net async-await c# entity-framework-6 task-parallel-library

Question

I believe that my comprehension of how this is meant to operate might be incomplete. A file is imported by some code I have. It does some processing on each record in a loop before adding that record to a table.DbContext instance.

I start overDbContext as in this:

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

    _db = new AppDBEntities();
    _db.Configuration.AutoDetectChangesEnabled = false;
    _db.Configuration.ValidateOnSaveEnabled = false;
}

This is how my main loop appears:

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

_db.SaveChanges();

ProcessRecord looks similar to this:

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();
    }
}

I just made minor adjustments forSaveChangesAsync() aimed to addasync Task<int> as a return type forProcessRecord , alteredSaveChanges() to return await SaveChangesAsync() then deleted the call toResetDBContext.

Before the async adjustments, everything functioned as intended. It appears that not all of my records are being saved after that.

What do I not see here?

1
4
9/23/2014 3:14:45 PM

Accepted Answer

When you dial anasync function that returns a job right away, before it has finished. You must utilizeawait to asynchronously before playing the following record. The practice of naming yourasync methods ending in "Async":

foreach (var rec in engine)
{
    var record = new CommonImportRecord(rec);
    var result = await ProcessRecordAsync(record, options, index);
    index++;
}
11
9/23/2014 2:08:33 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow