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
}
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
If you are on framework 4.5 you can use IRegisteredObject implementation as suggested in this post
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.