I am developing a heavy MVC routine that will delay some minutes to process. Then I call an Ajax request and I would like to send an answer from controller to interface if the process has started correctly and to keep executing it using a Thread. However, when the return is sent, it is needed to access the database, and I have the following error: Object disposed.
My code:
var entidade = this._repositorioDeTabelaDePremiacaoUPL.ObterPorID(dto.ID);
if(entidade.StatusDoServico == ListaDeStatusDoServico.tcProcessando.Id)
return Content("{success:false}");
Thread thread = new Thread(() => this._servicoDeTabelaDePremiacaoUPL.GerarTabela(dto));
thread.Start();
GerenciadorDeUnidadeDeTrabalho.Corrente.Commit();
return Content("{success:true}");
I suggest to use an extra db context for your thread and dispose it at the end. Because your db context for your web application and extra thread have different lifecycles. For web application it is generealy per HttpContext – web request and for thread is it the lifespan of the thread. You can create new instance of your db context at own or use some Conditional object construction.
Notes:
It is not a very good practice to reuse your db context for whole lifecycle of your application and reference it as static property (it could lead in concurrency issues and the entities state inside the context could become inconsistent). Better approach is to register your db context in HTTPContext scope (
InstanceScope.HttpContext) and then use constructor injection on your controllers.Global.asax
Controller