问题
I have an ASP.Net application which fires off some background workers using ThreadPool.QueueUserWorkItem(). Most of the time there will be zero background threads running, however it's possible that there could occationally be up to 5-6 executing at a time. Additionally, most will complete within a couple seconds, but it is possible that they could run for as long as 10 minutes.
Given all the different scenarios that could cause a shutdown of an ASP.Net application, I'd like to have these background processes exit gracefully if possible when the application needs to shutdown and they are in the middle of processing.
I don't anticipate having too much of an issue creating a way to signal the processes to stop their work early and clean up within a few seconds of getting the call that the application is being shut down. Although if anyone has specific advice on this I'd certainly appreciate it.
My two main questions are:
1) When would be the appropriate time to tell the background workers to wrap things up. During Application_End? Dispose()? Or perhaps a third option I'm not aware of.
2) If I wait during the above event for the processes to finish before returning, is there a point where not having Application_End return immediately could cause more serious issues for the application than not shutting down the background jobs nicely.
void Application_End(object sender, EventArgs e)
{
//if this for whatever reason takes a non-trivial time to execute, what problems could I encounter?
SignalBackgroundJobsAndWaitForThemToShutDown();
}
Thanks!
回答1:
The appropriate time is on the Application_End
Now after you signal your background jobs you must wait for them at that point to end, and then let continue, as its seems that you do.
Have in mine, that is good to place a time out on the wait, not wait for ever or else your pool may have problems, or shutdown, then you need to check your pool setting on the max wait to shutdown the pool, there set a value larger than your wait, or just disabled it.
Also have in mine that if you have pool garden, (more than 1 working pools) then the Application_End is called one time for each pool.
I use the same technique on my sites, the same way I signal my threads to stop the same way, I just also log the final end, and check when they are final end, and also I force my routines to stop and not let them run for many time. The Application_End is called on recycle the pool, or when you open the app_offline.htm file, or when you go to close the web service. Personally I have disable the recycles, I do not need them and I only open the app_offline.htm when I make updates. At that moment I wait my pool threads to stop their work.
来源:https://stackoverflow.com/questions/4617613/application-end-and-background-processes-exiting-asp-net-application-gracefully