Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does main thread wait for child thread completion?

I have .net core on Windows and simple code. As you can see, there is no Join() present. So main thread doesn’t wait for child, but when I run:

C:\...\bin\Release\netcoreapp3.1>dotnet ConsoleAppTest.dll
> 4
> mission complete
> Thread complete

C# code:

static void Main(string[] args)
{
    new Thread(() =>
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(10000);
        Console.WriteLine("Thread complete");
    }).Start();

    Console.WriteLine("mission complete");
}

I thought main thread should run and not wait for child. Am I wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I launch

 Task.Run(() =>
            {
                Thread.Sleep(10000);
                Console.WriteLine("Thread complete");
            });

main thread doesn’t wait

>Solution :

From Thread.IsBackground documentation:

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.

And

By default, the following threads execute in the foreground (that is, their
IsBackground property returns false):

  • The primary thread (or main application thread).
  • All threads created by calling a Thread class constructor.

You are creating foreground thread which prevents your process from terminating.

Also note that working with threads directly since the introduction of TPL is usually not recommended but if there is a particular reason making you to use them you can set the IsBackground property to true to allow the process to terminate:

var thread = new Thread(() =>
{
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(1000);
    Console.WriteLine("Thread complete");
});
thread.IsBackground = true;
thread.Start();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading