7

I am using EF6, MVC 5 in VS 2013. I have a long-running task which is causing timeout errors and so I want to set it running as a separate background task and return immediately to the web controller. The background task will report progress to an SQL server database. What I need, essentially, is fire and forget functionality. There appear to be a number of options:

  1. Write the task's details to a server and use a Windows service to process them UPDATE: this was the options used
  2. Use async - this does not seem to be a safe option
  3. Use HostingEnvironment.QueueBackgroundWorkItem method

Option 3 would be preferred as it keeps all the code in one solution. Please could you comment on the pros and cons of each and point, if possible, working examples of number 3?

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Peter Smith
  • 5,528
  • 8
  • 51
  • 77
  • 1
    Or [ASP.NET long running task. Thread is being aborted exception](http://stackoverflow.com/questions/16254567/asp-net-long-running-task-thread-is-being-aborted-exception), [How to implement a very long running background task in Asp WebAPI application](http://stackoverflow.com/questions/21153329/how-to-implement-a-very-long-running-background-task-in-asp-webapi-application), [Long Running Tasks - Best Practice - ASP.NET 4.0, C#](http://stackoverflow.com/questions/9577112/), and so on. Type "asp.net long running task" in your favorite search engine and go read why you want option 1. – CodeCaster Jan 27 '15 at 11:53
  • 1
    @CodeCaster thanks. I did write it as a Windows service. It has now been running quietly and effectively since then. – Peter Smith Nov 01 '16 at 07:37
  • thanks, good to hear. – CodeCaster Nov 01 '16 at 08:57

1 Answers1

9

HostingEnvironment.QueueBackgroundWorkItem is a valid solution, but keep in mind that the long-running process may be interrupted, for example if application pool recycles.

A better option would be to run it in a scheduled task, for example using Quartz.NET.

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
L-Four
  • 13,345
  • 9
  • 65
  • 109