I did not find similar questions/answers for my purpose.
In few Actions of my Controllers (MVC 4/ EF 5 application) I have functions for updating of database, but these functions are not affect on user output (functions of updating information after selecting). And I want to send these functions in asynchronous threads (which will finished after user get a rendered page). I do not want to wait finishing of threads and render page. What about database context in this case? My context lifetime is "per request" and it deletes in Application_EndRequest:
protected virtual void Application_EndRequest()
{
var entityContext = HttpContext.Current.Items["_Context"] as DbContext;
if (entityContext != null)
entityContext.Dispose();
}
I use own contexts in threads (using blocks for correct disposing).
using (DbContext db = new DbContext())
{
....
}
But if I want to Attach entity to DbContext in thread I get an error "An object with the same key already exists in the ObjectStateManager" in several cases. It is weird, because I use loading with AsNoTracking() option and entity state is "detached" in main Context before call new thread. In other case, when I am trying the request entity from database once again in thread and modify it (instead of attaching) I have an error "The object is in a detached state" several times Are the two instance of Context using one ObjectStateManager? And errors appear in dependence on time of main thread Context disposing. I mean before or after disposing main Context I use context in thread...
How can I work with asynchronous threads with own Context in this situation? Thanks.