在我的 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/