Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Join versus Task.Wait

Consider the following code.

Thread

static void Main(string[] args)
{
    Thread t = new Thread(Foo);
    t.Start();

    Console.WriteLine("Main ends.");
    //t.Join();
}

static void Foo()
{
    for (int x = 0; x < 1000000000; x++) ;

    Console.WriteLine("Foo ends.");
}

Task

static void Main(string[] args)
{
    Task t = new Task (Foo);
    t.Start();

    Console.WriteLine("Main ends.");
    t.Wait();
}

static void Foo()
{
    for (int x = 0; x < 1000000000; x++) ;

    Console.WriteLine("Foo ends.");
}

When using Task, we need t.Wait() to wait for the thread pool thread to complete before the main thread ends but when using Thread, we don't need t.Join to get the same effect.

Question

Why is t.Join() not needed to prevent the main thread from ending before the other spawned threads end?

like image 214
xport Avatar asked Oct 13 '16 18:10

xport


1 Answers

There are several differences, but the important part to answer your question is that the thread pool uses background threads, and these do not block the process from exiting. You can read more here.

like image 167
Amit Avatar answered Oct 16 '22 18:10

Amit