Consider the following code.
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.");
}
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.
Why is t.Join()
not needed to prevent the main thread from ending before the other spawned threads end?
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.
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