0

I am new to c# i know whats are the threads but i cant really explain following example.

static void Main()
{
    new Thread(new ThreadStart(test))
    {
        IsBackground = true
    }.Start();
}

static void test()
{
    while (true)
    {
        Console.WriteLine("Threads: ");
    }
}

Here my program doesnt spam.
When i tried to use

static void Main()
{
    test();
}

static void test()
{
    while (true)
    {
        Console.WriteLine("Threads: ");
    }
}

Now loop never ends.Why? When i use threads loop is not infinity. Sorry for my bad english

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49

1 Answers1

1

When your main program exits, the threads will be killed.

You can either pause the main program, for example by waiting on Console input:

static void Main() {
    new Thread(new ThreadStart(test))
    {
        IsBackground = true
    }.Start();
    Console.Read();
}

Or wait for the thread explicitly:

static void Main() {
    var thread = new Thread(new ThreadStart(test))
    {
        IsBackground = true
    }.Start();
    thread.Join();
}

A more real-world example would use a ManualResetEvent or CancellationToken inside the thread, so it knew when to stop instead of an infinite loop ofcourse

Milney
  • 6,253
  • 2
  • 19
  • 33
  • 2
    Or don't create the thread as a Background thread.. Foreground threads (IsBackground = false) will keep the program alive. If Main returns but there are still foreground threads the process won't exit. – pinkfloydx33 Sep 06 '20 at 14:27
  • @pinkfloydx33 Think that may depend on the host though right? Sure in most scenarios that would work though – Milney Sep 06 '20 at 14:39
  • Just look at the docs. The examples for IsBackgroundThread show two threads started (one BG, onc FG) and Main ending (without calling Join). The program is kept alive until the FG thread ends. The 'BG vs FG threads' doc also describe it that way – pinkfloydx33 Sep 06 '20 at 14:43