c# - queuebackgroundworkitem - web api long running task




Queue-Based Background Processing in ASP.NET MVC Web Application (2)

How can I implement background processing queues in my ASP.NET MVC web app? While most data changes, updates etc. need to be visible immediately, there are other updates that don't need real time processing which I would like to hand off to a lower-priority background process which will take care of it at its own pace.

As an example, take StackOverflow's badge award system. Usually you may take a specific action that would award you a badge, but the actual 'award' happens later (typically between 10 minutes and a couple hours later). I assume this is done via a separate background process as it is not critical for SO's workings to award badges immediately when earned.

So, I'm trying to create some kind of queue system in which I could stuff tasks (say anything implementing ITask interface which will have a Process() method) which will eventually get executed by a separate process.

How would I go about implementing such a system? Ideas/Hint/Sample Code?

Thank you!


Jeff has a great post showing how he achieved this originally for at http://blog..com/2008/07/easy-background-tasks-in-aspnet/

While it might not be as reliable as a service if that's an option to you, it's served me well in the past for non essential tasks, and I've had it working in a virtual hosting environment.


Just found this question when searching for background process in ASP.NET MVC. (Available after .NET 4.5.2)

public ActionResult InitiateLongRunningProcess(Emails emails)
{
    if (ModelState.IsValid)
    {
       HostingEnvironment.QueueBackgroundWorkItem(ct => LongRunningProcessAsync(emails.Email));
       return RedirectToAction("Index", "Home");
    }

    return View(user);
}

Note: Personally I won't use the Webserver to run background tasks. Also don't reinvent the wheel, I would highly recommend to use Hangfire.

Read this great article from Hanselman HowToRunBackgroundTasksInASPNET





asp.net-mvc