articles

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

Foreground and Background thread in C# Threading

Anonymous User16791 26-Aug-2011

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.

usingSystem.Threading;
 
namespaceForegroundThread
{
    classProgram
    {
        staticvoidMain(string[] args)
        {
            // Create ThreadA object
            Threadback= newThread(newThreadStart(ChildThreadA));
            // Create ThreadB object
            Threadfore= 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);
            }
 
       }
        publicstaticvoidChildThreadA()
        {
            for (inti=0; i<10; i++)
            {
                Console.WriteLine("Child thread A:");
            }
        }
        publicstaticvoidChildThreadB()
        {
            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

 


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By