Search code examples
c#multithreadingbackground-thread

Background Thread is not working as mentioned in any of its definitions


Definition: A Background tread stops executing when the Main thread leaves the execution.

Source

When I try it out, the background thread did not stop the execution even when the main thread completes the execution. Please check the example provided for Background Thread in the above link.

using System; using System.Threading;

class GFG {

// Main method 
static void Main(string[] args) 
{ 
    // Creating and initializing thread 
    Thread thr = new Thread(mythread); 

    // Name of the thread is Mythread 
    thr.Name = "Mythread"; 
    thr.Start(); 

    // IsBackground is the property of Thread 
    // which allows thread to run in the background 
    thr.IsBackground = true; 

    Console.WriteLine("Main Thread Ends!!"); 
} 

// Static method 
static void mythread() 
{ 

    // Display the name of the  
    // current working thread 
    Console.WriteLine("In progress thread is: {0}", 
                        Thread.CurrentThread.Name); 

    Thread.Sleep(2000); 

    Console.WriteLine("Completed thread is: {0}", 
                      Thread.CurrentThread.Name); 
} 

}

Expected Output : In progress thread is: Mythread Main Thread Ends!!

I did not get the output as they have mentioned there. I got all three console outputs like

In progress thread is: Mythread Main Thread Ends. Completed thread is: Mythread

Edit: Some say Unable to repro the issue. Am I the only one who is facing this issue?

enter image description here


Solution

  • enter image description here

    Attached the snapshot. Result is as expected in documentation. I am using VS 2019 , .Net 3.5