7
class Program
{
    public static void Main(String[] args)
    {
        var c = new C();
        var thread = new Thread(new ThreadStart(c.F));
        thread.Start();
        Console.WriteLine("Exiting main, but the program won't quit yet...");
    }
}
class C
{
    public void F()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Waiting {0}", i);
            Thread.Sleep(1000);
        }
        Console.WriteLine("Now the program will quit...");
    }
}

What's going on under the hood with a console application that leads to it waiting for the other thread to finish before exiting (pointer to docs fine)?

Note: I know this is a basic question - I just always managed waiting for threads to finish before and never considered there was some infrastructure that did it for me...

Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121
  • 3
    see remarks on Thread.IsBackground @ http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx. A process ends when all foreground threads terminate. – drch Jan 31 '13 at 02:04
  • @drch, that's basically the answer. Why a comment? – MSN Jan 31 '13 at 02:10
  • @drch, before I posted this I was googling trying to find exactly that.. thanks! (and if you put it in I'll mark in answer) – Aaron Anodide Jan 31 '13 at 02:15

2 Answers2

11

A process ends when all foreground threads terminate

From Thread.IsBackground remarks on foreground threads vs background threads:

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

drch
  • 3,040
  • 1
  • 18
  • 29
-1

Any process which has running thread will not exit till all the threads are exited. So when the main thread exits it has another thread running and when the tread exits process gets terminated. To exit the program at any point of time Environment.Exit(0); should work. This statement will terminate all the treads and process will be terminated this is ungraceful way though

sumeet kumar
  • 2,628
  • 1
  • 16
  • 24