c# - 在此上下文中开始了第二个操作

标签 c# asp.net entity-framework

在我的 Controller 中,我在保存到数据库的日期之后执行另一个 Void 函数。但有时它会显示此错误:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

...这是我的 Controller 示例:

public ActionResult All(Chapter chapter){

    var x = db.Post.Where(p => p.PostID == chapter.PostID).FirstOrDefault();
    if (x == null){return View(chapter);}

    counter++;

    db.Chapter.Add(chapter);
    db.SaveChangesAsync();                      

    savepost(chapter.PostID, counter);

    return RedirectToAction("Index");
}

这里是 Void 方法:

public void savepost(int id,int counter)
{
    var article = db.Post.Find(id);
    article.LastUpdate = DateTime.Now;
    article.ChapterCount = counter;

    db.Entry(article).State = EntityState.Modified;
    db.SaveChanges();
}

我该如何解决这个问题?

最佳答案

最短的修复:

//db.SaveChangesAsync(); 
db.SaveChanges(); 

稍微好一点的选择:

public async Task<ActionResult> All(Chapter chapter)
{
   ....
   await db.SaveChangesAsync(); 
   ...
}

您没有等待对 SaveChangesAsync() 的调用,这意味着它将(可以)在单独的线程上 fork 。然后它给你这个错误,一个 DbContext 不能在线程之间共享。

作为练习,您可以对 SavePost() 方法进行类似的更改:

  • 让它成为一个async Task方法
  • 将 SaveChanges() 替换为 await db.SaveChangesAsync()
  • 等待调用 SavePost()

关于c# - 在此上下文中开始了第二个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138888/

相关文章:

c# - 在我的 owin 授权提供程序中的 GrantResourceOwnerCredentials 中设置自定义主体后,HttpContext.Current.User.Identity.Name 为空

c# - 从 Windows 移动应用程序获取文件的图标

c# - 有什么方法可以用 Mono(.net) 获取 FileDescriptor?

c# - 正确运行 SerializeObject 方法?

c# - Entity Framework 4 中的多对多查询

c# - EntityFramework Core 自动生成键 id 属性

c# - Razor View 中的简写 If without else (ASP.NET MVC4)

javascript - ASP.NET:UpdateProgress 不适用于具有 ClientIDMode ="Static"的控件

c# - 在删除之前更新实体

c# - "Cannot insert explicit value for identity column in table ' 电影 ' when IDENTITY_INSERT is set to OFF."