Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a multithreaded console application exit?

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...

like image 823
Aaron Anodide Avatar asked Jan 31 '13 02:01

Aaron Anodide


1 Answers

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.

like image 83
drch Avatar answered Nov 03 '22 00:11

drch