Home > DeveloperSection > Articles > Foreground and Background thread in C# Threading

Foreground and Background thread in C# Threading


C# C# 
Ratings:
0 Comment(s)
 10296  View(s)
Rate this:

Foreground and Background thread in C# Threading

By default, When we create thread is implicitly foreground thread, foreground thread keeps application is alive as long as any one of foreground thread is active where as  background thread do not. When all foreground thread is terminated then background thread implicitly terminated.

Foreground and background does not affect to each other.

Example:

To creating Foreground and Background thread writes the following code.

using System.Threading;

 

namespace ForegroundThread

{

    class Program

    {

        static voidMain(string[] args)

        {

            // Create ThreadA object

            Thread back= newThread(newThreadStart(ChildThreadA));

            // Create ThreadB object

            Thread fore= newThread(newThreadStart(ChildThreadB));

            // Set ThreadB as background thread

            back.IsBackground= true;

            back.Start();

            fore.Start();

            

            Thread.CurrentThread.Name= "Main";

            for (inti=0; i<20; i++)

            {

                if (i==5)

                     fore.Abort();  //Abort Foreground thread

               Console.WriteLine(Thread.CurrentThread.Name);

            }

 

       }

        public staticvoidChildThreadA()

        {

            for (inti=0; i<10; i++)

            {

                Console.WriteLine("Child thread A:");

            }

        }

        public staticvoidChildThreadB()

        {

            for (inti=0; i<10; i++)

            {

                Console.WriteLine("Child thread B:");

            }

        }

    }

}

 

In above program after terminating of foreground thread the application will run until main thread is not terminated after terminating main thread application will be terminate.

Output:

Foreground and Background thread in C# Threading

 


Don't want to miss updates? Please click the below button!

Follow MindStick