A second operation started on this context

Viewed 1230

In my Controller I execute another Void Function after the date saved to DB. But sometimes it's show this error :

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.

...and here is a sample of my 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");
}

and here is the Void method:

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

How i can solve this ?

1 Answers

Shortest fix:

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

the slightly better option:

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

You were not awaiting the call to SaveChangesAsync(), meaning it will (can) be forked off on a separate thread. And then it gives you this error, a DbContext cannot be shared beween threads.

As an exercise, you can make a similar change to the SavePost() method:

  • make it an async Task method
  • replace SaveChanges() with await db.SaveChangesAsync()
  • await the call to SavePost()
Related