Daniel
Daniel

Reputation: 393

Background thread does not stop when foreground thread stop?

When I'am running the example provided in the following link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.isbackground?view=netframework-4.8

class Example
{
    static void Main()
    {
        BackgroundTest shortTest = new BackgroundTest(10);
        Thread foregroundThread = 
            new Thread(new ThreadStart(shortTest.RunLoop));

        BackgroundTest longTest = new BackgroundTest(50);
        Thread backgroundThread = 
            new Thread(new ThreadStart(longTest.RunLoop));
        backgroundThread.IsBackground = true;

        foregroundThread.Start();
        backgroundThread.Start();
    }
}

according to the documentation,the background thread should stop when the foreground thread stops.I run this example on my computer and the background thread does not stop and continues to print the numbers in the for loop.Also,the number ten is printed only once, not twice as in the example , as the for loop is running from 0 to 9.This is the output that I receive from the example,without making any modifications to the example:

https://pastebin.com/AsfEX6gf

Is it the documentation wrong or it depends on the CPU architecture ?

Upvotes: 0

Views: 215

Answers (1)

Gleb
Gleb

Reputation: 1761

I tried it with diferent CLR's and I used both .Net Framework and .Net Core - works as it should work. But as mentioned in the comments section if you put Console.Readline() at the end of your Main function - it blocks your main thread until you provide an input and since your main thread is a foreground thread - the background thread keeps on counting.

Upvotes: 4

Related Questions