views:

32

answers:

2

I have a controller whose main function is to save data. The ajax call that saves this data needs to be executed quickly.

What I want to do is get the POST in the controller and spin off a background thread that will do the actual work to save the data; this would allow me to do return view() instantly. So essentially the only lag it would take is to spawn the background thread - which should be milliseconds.

I tried doing this by using a backgroundworker

public ActionResult Save(){
using (BackgroundWorker worker = new BackgroundWorker())
                    {
                        worker.DoWork += new DoWorkEventHandler(blah);
                        worker.RunWorkerAsync(Request.Form["data"]);
                    }
return View();
}

However, this call still takes a while, making me think that the background worker needs to get executed before the View is returned.

Any ideas on how to do this so that the view is returned instantly (while the background worker processes the data in the background for however long it takes)?

A: 

Try spinning a thread manually to see if it makes any difference:

public ActionResult Save()
{
    new Thread(blah).Start(Request.Form["data"]);
    return View();
}
Darin Dimitrov
+1  A: 

I would suggest dumping the data into a database or some other external storage and use a separate process to do the work (perhaps a Windows Service or a job scheduling tool like Quartz.NET).

With the possibility that ASP.NET could re-cycle the worker process (due to memory load or other triggers), you risk losing the work being done in the background threads (as well as running out of threads if there's a high number of requests to this action).

Patrick Steele