Search code examples
asp.net-mvcasynchronousbackground-process

.Net MVC - Background process implementation with HostingEnvironment.QueueBackgroundWorkItem


I am looking for something like a background process in MVC.

Requirement is I should run a background process/thread in .Net MVC application, which will be async and doesn't wait for the action in the foreground/ UI. Similar to fire and forget.

I am trying to use HostingEnvironment.QueueBackgroundWorkItem for the same. Can this be used or anything else is recommended ? I am armature in MVC, Thanks in advance.


Solution

  • If you want to use background job in controller HostingEnvironment.QueueBackgroundWorkItem is normal solution.

    For examle, start backgroud action and foget

     public class HomeController : Controller
        {
            [HttpPost]
            public ActionResult Index()
            {
                Action<CancellationToken> workItem = SomeBackGroundWork;
                
                // start background work and forget
                HostingEnvironment.QueueBackgroundWorkItem(workItem);
    
                return RedirectToAction("Home");
            }
    
            private async void SomeBackGroundWork(CancellationToken cancellationToken)
            {
                await Task.Delay(2000,cancellationToken);
    
                // or you can do http request to web site
                using (var client = new HttpClient())
                {
                    var response = await client.PostAsync("http://google.com",  new StringContent(""), cancellationToken);
    
                }
            }
         }