Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

.net - Long-running background process in ASP.NET - Application_Start or separate process?

I'm developing a .NET 4 application that requires a backend worker thread to be running. This thread consists mostly of the following code:

while (true) {
    //Check stuff in database
    //Do stuff
    //write to database / filesystem
    Thread.sleep(60000)
}

The ASP.NET app is just a frontend for the database.

My question is around where the best place to put this worker loop would be. It seems my immediate two choices would be (1) to spin it off from the Application_Start method, and just let it run, or (2) bundle it in a separate process (Windows service?)

(1) would obviously need some logic in the ASP.NET code to check it's still running, as IIS might kill it. It's also quite neat in that the whole application logic is in one, easily deployable package. (2) is much more segregated, but feels a lot messier.

What's the best approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would strongly opt for the Windows Service if possible. Background threading in ASP.NET comes with a lot of baggage.

  1. The lifetime of your background process is at the mercy of IIS. If IIS decides its time to recycle the App Pool, your background process will restart. If IIS decides to stop the App Pool due to inactivity, your background process will not run.
  2. If IIS is configured to run as a Web Garden (multiple processes per AppPool), then your background thread could run more than once.
  3. Later on, if you decide to load balance your website (multiple servers running the site), then you may have to change your application to ensure the background threading is only happening on one server).

And plenty more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...