Best ASP.NET Background Service Implementation

What’s the best implementation for more than one background service in an ASP.NET application?

  1. Timer Callback
    Timer timer = new Timer(new TimerCallback(MyWorkCallback), HttpContext, 5000, 5000);
  2. Thread or ThreadPool
    Thread thread = new Thread(Work);
    thread.IsBackground = true;
    thread.Start();
  3. BackgroundWorker
    BackgroundWorker worker = new BackgroundWorker(); 
    worker.DoWork += new DoWorkEventHandler(DoMyWork);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DoMyWork_Completed); 
    worker.RunWorkerAsync();
  4. Caching like http://www.codeproject.com/KB/aspnet/ASPNETService.aspx (located in Jeff Atwood’s post here)

I need to run multiple background “services” at a given time. One service may run every 5 minutes where another may be once a day. It will never be more than 10 services running at a time.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Well, instead of a ‘Simple Thread’, you’d go for a ThreadPool.

And if it were me, I’d run it in a Windows Service and communicate to it via MSMQ.

Method 2

You should implement some states of tasks. After application recycles background service should repair broken tasks. If tasks are under transactions then there will be no problems with that behaviour.

Method 3

None of the suggestions of the original poster scales to more than one server.

I want the same thing:
A robust and simple to use way of scheduling regular background tasks and perform ad-hoc heavy processing (rebuild caches and so on) without affecting the current users request.

I want to have the tasks run in web apps context, to a) get the config from web.config (avoid duplication of config) and b)be deployed with the web app (ease deployment).
And I need it to work for websites spread to more than one server.

I’ve only found one approaches that provides somewhat what I want:

(1) Create an .aspx page for each task and setup a wget scheduled task on one separate server that calls this .aspx on the website. I have implemented this approach and it works, but I do not like it 100%, because of the scheduled task dependency and it does not give me the ability to perform heavy tasks ad hoc in the background


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x