加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:44:20 所属栏目:百科 来源:网络整理
导读:我想我可能会错过一些关于这应该如何工作的东西.我有一些导入文件的代码.它遍历每个记录,进行一些处理,然后通过DbContext实例将该记录添加到表中. 我像这样初始化DbContext: protected void ResetDbContext(){ if (_db != null) _db.Dispose(); _db = new A
我想我可能会错过一些关于这应该如何工作的东西.我有一些导入文件的代码.它遍历每个记录,进行一些处理,然后通过DbContext实例将该记录添加到表中.

我像这样初始化DbContext:

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

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

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

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

_db.SaveChanges();

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

我为SaveChangesAsync()做的唯一真正的改变是添加异步Task< int>作为ProcessRecord的返回类型,更改了SaveChanges()以返回等待SaveChangesAsync()并注释掉对ResetDBContext的调用.

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

我在这里错过了什么?

解决方法

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

foreach (var rec in engine)
{
    var record = new CommonImportRecord(rec);
    var result = await ProcessRecordAsync(record,index);
    index++;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读