I read on MSDN that the difference between a foreground thread and a background thread is that an application can't terminate until all of its foreground threads have terminated, whereas it won't bother waiting for background threads. I decided to try this out just to get a better understanding of threads.
Thread t = new Thread(Work); //Work() just has the thread sleep for a long time
t.IsBackground = false; //make it a foreground thread
t.Start();
while(true)
{
if(Session["checker"] != null)
{
Session["checker"] = true;
System.Diagnostics.Debug.Write("I'm here!");
}
}
I used a session variable to know if the AppDomain has been restarted since sessions get cleared upon an AppDomain restart.
So when I save the web.config file, it should trigger the AppDomain to restart, which should require it to wait for my long running thread t since t is running in the foreground. However when I touch the web.config file, goes straight into clearing my Session["checker"] and printing out "I'm here!", so I know that my application didn't wait for my thread.
Am I misunderstanding how foreground threads are supposed to work? Shouldn't the AppDomain restart wait for my thread to finish executing before it goes and starts clearing my session variables?
Thanks
Please, pay attention to the word "application" in statement "application can't terminate until all of its foreground threads have terminated". In case of recycling, application is not terminated. During recycling ASP.NET is unloading old AppDomain and loading new one. Everything is done inside single process. Process isn't terminated. In scope of AppDomain unloading, all threads (Background and Foreground) are killed. So, ASP.NET won't wait for foreground threads to complete during recycling. Try simple console application which creates a Foreground thread in its Main method. It will work until the thread is terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With