Entity Framework SaveChanges Async

asynchronous c# entity-framework entity-framework-6 task

Question

I am currently working on an audit trail feature and using the entity framework.

the current code works but takes long time to run.

public class MyDbContext : DbContext {

  public int SaveChanges() {
    // get changes from ChangeTracker.DetectChanges()

    // generate custom audit trail records

    return base.SaveChanges();
  }
}

I was thinking of moving the audit trail building after the save changes and doing it async

public int SaveChanges() {
  // get changes from ChangeTracker.DetectChanges()

  int ret = base.SaveChanges();

  // call async function to create audit

  return ret;
}

I have tried using async-await but I encountered problems where the object has been disposed. I'm not really used to threading/async calls.

Is there like a way to do a "partial" return where the parent process gets the desired return inorder to continue its process, while the object is still alive/not-disposed to continue the async task.

public int SaveChanges() {
  // get changes from ChangeTracker.DetectChanges()

  int ret = base.SaveChanges();

  // partial return ret;

  // continue process in generating audit trail
}
1
0
7/18/2017 3:04:48 PM

Popular Answer

In your scenario using Async Await may not work as in cases where your background process outlive the lifetime of parent process you may face situations like the one you are facing.

If you are running framework 4.5.2 or if you can upgrade to that then the best option in your scenario would be to use QueueBackgroundWorkItem API.Below are links for usage

http://codingcanvas.com/using-hostingenvironment-queuebackgroundworkitem-to-run-background-tasks-in-asp-net/

http://blogs.msdn.com/b/webdev/archive/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-long-background-process-in-asp-net.aspx

If you are on framework 4.5 you can use IRegisteredObject implementation as suggested in this post

http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/

0
11/12/2014 3:56:59 AM


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