views:

50

answers:

1

I have an asp.net application with a background thread. The thread starts when the application starts and it is gracefully stopped when the application ends. I am running the website on a shared host. Unfortunately sometimes the application does not trigger the Application_End event when it ends. I would think that the threads would be killed anyway, but that's not the case. I currently have 4 threads running in the background. Three from previous times the application started and 1 from the current application session. How can I ensure that the threads are shutdown when the application ends? Is there a way for the threads to check if the application was reset or had been reset? Or is there a way to check for these rogue threads at application startup and kill them? Thanks in advance.

+3  A: 

Use the ThreadPool.QueueUserWorkItem() to execute your code in the background, which will be ended when the AppDomain unloads. I'm assuming that you are using a backgroundworker, according to the tags, and I would suggest trying this instead. (Consider adding sample code to draw out better answers.)

Managed ThreadPool: http://msdn.microsoft.com/en-us/library/0ka9477y.aspx

Foreground/Background Threads: http://msdn.microsoft.com/en-us/library/h339syd0.aspx

umbyersw
Thank you for this info, I did not know about the managed thread pool. From the examples you showed me it looks like it works for running a thread on a function in the same class. But I am using a separate instantiated class as the thread. Will it work in that case as well? What is the trade-off between using Managed ThreadPool and setting the IsBackground property to true as Ani mentioned above?
Noel
Also the reference you provided states "If you have short tasks that require background processing, the managed thread pool is an easy way to take advantage of multiple threads." I am afraid this is not the case as my thread will be alive for the duration of the application's life.
Noel