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:
Anonymous User
06-Jul-2019Thank You.