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?
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
IsBackgroundproperty returnsfalse):
- The primary thread (or main application thread).
- All threads created by calling a
Threadclass 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();