3

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

hemlocker
  • 1,012
  • 1
  • 9
  • 24
  • ASP.NET will terminate all threads, when it recycles the app pool. Not sure if ASP.NET has a clear distinction between background and foreground threads (though you could probably invent one, with enough creativity). – Chris O Jul 12 '12 at 21:39

1 Answers1

4

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.

Raman Zhylich
  • 3,537
  • 25
  • 23
  • Thank you Raman, I had assumed that application termination is a part of the AppDomain unloading. I guess it isn't :) – hemlocker Jul 12 '12 at 21:59