Forground and Background threads

There are 2 types of threads, namely foreground and background threads.
Foreground Thread - The process will alive till atleast one thread is alive. By default threads are foreground threads.
Background Thread - The process will exit until all the foreground threads in the application live. If all the foreground threads are completed or stopped, then the application will exit and dont wait for the background threads to be finished.



namespace My_Samples
{
using System;
using System.Threading;

public class MyClass
{
public void MyMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("MyMethod - " + i.ToString());
Thread.Sleep(100);
}

Console.WriteLine("MyMethod is completed...");
}
}

class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
ThreadStart entryPoint = new ThreadStart(obj.MyMethod);
Thread thread = new Thread(entryPoint);
thread.Start();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Main Method - " + i.ToString());
Thread.Sleep(10);
}
Console.WriteLine("Main method is completed...");
}
}
}


The output will be something as below.


Main Method - 0
MyMethod - 0
Main Method - 1
Main Method - 2
Main Method - 3
Main Method - 4
Main Method - 5
Main Method - 6
Main Method - 7
Main Method - 8
Main Method - 9
MyMethod - 1
Main method is completed..
MyMethod - 2
MyMethod - 3
MyMethod - 4
MyMethod - 5
MyMethod - 6
MyMethod - 7
MyMethod - 8
MyMethod - 9
MyMethod is completed...


Though I hit enter or even after the main method terminates, the application still alive as the MyMethod thread is running. Let's change the code as below.



namespace My_Samples
{
using System;
using System.Threading;

public class MyClass
{
public void MyMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("MyMethod - " + i.ToString());
Thread.Sleep(100);
}
Console.WriteLine("MyMethod is completed...");
}
}

class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
ThreadStart entryPoint = new ThreadStart(obj.MyMethod);
Thread thread = new Thread(entryPoint);
thread.IsBackground = true;
thread.Start();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Main Method - " + i.ToString());
Thread.Sleep(10);
}
Console.WriteLine("Main method is completed...");
}
}
}


When you run this application you will see the below output and the application terminates immediately.


Main Method - 0
MyMethod - 0
Main Method - 1
Main Method - 2
Main Method - 3
Main Method - 4
Main Method - 5
Main Method - 6
Main Method - 7
Main Method - 8
Main Method - 9
MyMethod - 1
Main method is completed..

Ok.. now the question is what happened my background thread. Lets see that in next article.

No comments:

Post a Comment