I have an ASP.NET MVC 3 (.NET 4) web application.
I have a [HttpPost] action method which submit’s some data to the database.
Now, after this method is finishing persisting to the repository, i wish to execute a “background” task (think auditing, or sending an email, etc), where i don’t care about the result (unless an error occurs, in which case i’ll perform logging).
How can/should i fire off this task from my action method?
[HttpPost]
[Authorize]
public ActionResult Create(MyViewModel model)
{
if (ModelState.IsValid)
{
_repo.Save(model);
// TODO: Fire off thread
return RedirectToRoute("Somepage", new { id = model.id });
}
return View(model);
}
The new .NET 4 way to do this is with a
Task.http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx
But for this simple operation where you just want to run it and don’t care about coordinating tasks, it’s just as easy to use the ThreadPool.
You want to avoid creating a new Thread yourself for every action–it’ll take up more resources and is unnecessarily wasteful.
If you’re background tasks are longer running you might want to setup a producer/consumer queue and have a single or set number of constantly running background threads to run the tasks.