0

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

AjithKumar
  • 21
  • 6
  • Please post also your code into the question, not just the example. – jason.kaisersmith Mar 08 '20 at 08:48
  • Can you check setting the `IsBackground` property before `Start()`? – Theodor Zoulias Mar 08 '20 at 09:02
  • Yes. Already tried it. It did not work. Got the same result – AjithKumar Mar 08 '20 at 09:09
  • I cannot reproduce this issue. – Michał Turczyn Mar 08 '20 at 09:38
  • @Michal May I know where you are trying it? I created a .Net Console Application and using Visual Studio IDE. Did you exactly copy-paste this code? – AjithKumar Mar 08 '20 at 10:07
  • @AjithKumar Same soltuion, same IDE and copy-pasted code – Michał Turczyn Mar 08 '20 at 10:12
  • No i don't get the expected output. So you mean to say you got this as your output? In progress thread is: Mythread Main Thread Ends!! – AjithKumar Mar 08 '20 at 10:14
  • The comment is wrong. IsBackground must be *false* to prevent the program from terminating. – Hans Passant Mar 08 '20 at 11:33
  • 2
    In the screenshot I can see the line `Console.ReadLine()` that does not exist in the code sample. This line makes all the difference. – Theodor Zoulias Mar 08 '20 at 13:46
  • 1
    @TheodorZoulias Console window disappears as soon as it completes the execution. We can't witness the output then. I added Readline, so it will wait for some user input.so, we can check the output. Yes, you may be right. As we are waiting to read something, the main thread is still active. As the main thread is active, the background thread also executes completely. Thanks – AjithKumar Mar 08 '20 at 14:09
  • 1
    You can prevent your Console applications from closing, when running them from inside the Visual Studio, by starting them without debugging (with Ctrl + F5). The message `Press any key to continue . . .` will appear in the console when the application has completed. – Theodor Zoulias Mar 08 '20 at 16:14

3 Answers3

1

enter image description here

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

knowdotnet
  • 839
  • 1
  • 15
  • 29
  • Attached the screenshot of what I got as an answer. Please check. – AjithKumar Mar 08 '20 at 10:20
  • .Net 3.5? That's an old version! – Theodor Zoulias Mar 08 '20 at 13:50
  • I guess I got the mistake I made here. The console window disappears as soon as it completes the execution. I added Readline, so it will wait for some user input.so, we can check the output. As we are waiting to read something, the main thread is still active. As the main thread is active, the background thread also executes completely. Thanks. Appreciate your help, mate – AjithKumar Mar 08 '20 at 14:11
0

Place the IsBackground property before the Thread starts, like this :

// 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"; 

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

    Console.WriteLine("Main Thread Ends!!"); 
}
ShiningLea
  • 132
  • 1
  • 12
-1

The thread is launched as part of the "main" execution context. So upon exiting "main" "thr" will get collected and terminated since it is an instant part of the main program. Secondly "thr" started, sleep for 2 seconds and exited doing exactly what you told it to do. If the "thr" is intended to stay running then it needs to contain a loop of some kind and a signaling implementation to tell it to exit when it is not needed anymore.

I have not tried this yet but add the following to experiment. It might work closer to what you are tryimg to do but it is not a good way to do this.

static void mythread() 
{ 

  Do{
// 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); 
 }
While(sinalvariable) // signal variable changed by some other code 
                      //To tell thread  to exit the whileloop

} 

If you want code to stay loaded and running after the main exiting the initial code, you need to use a different strategy. You need to launch the code as "Process".

I can not give a complete answer as the probLem is not clear.

Your program is doing exactly what it need to do.

  • First thing, My intention is to understand the difference between the background thread and the foreground thread. As my question says, the background thread is not working as per its definition. The code that I have given you is taken from the famous geeks for geeks blog. It is not working as it was mentioned. It is not exactly doing what I have told to do. Please check the expected output that I have mentioned. And then, you said "the thread is launched as part of the main thread" if I am not wrong all threads have to be created using main thread. What ways we create new threads then? – AjithKumar Mar 08 '20 at 09:57