Best ASP.NET Background Service Implementation

只愿长相守 提交于 2019-11-30 07:51:36

问题


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.


回答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.




回答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.




回答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



来源:https://stackoverflow.com/questions/1424837/best-asp-net-background-service-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!