Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top