Foreground and background threads

By default, when a thread is created, it is created as a foreground thread. You can use the IsBackground property to make a thread a background thread. The main difference between foreground and background threads is that a background thread does not run if all the foreground threads are terminated. The runtime aborts all the background threads when foreground threads are stopped. If a thread is created using a thread pool, then these threads are executed as background threads. Note that when an unmanaged thread enters the managed execution environment, it is executed as a background thread.

Let's jump into an example to understand the difference between foreground and background threads:

public static void BackgroundThread()
{
Console.WriteLine("Thread Id: {0}" + Environment.NewLine + "Thread State: {1}" + Environment.NewLine + "Priority {2}" + Environment.NewLine + "IsBackground: {3}",
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.ThreadState,
Thread.CurrentThread.Priority,
Thread.CurrentThread.IsBackground);
var th = new Thread(ExecuteBackgroundThread);
th.IsBackground = true;
th.Start();
Thread.Sleep(500);
Console.WriteLine("Main thread ({0}) exiting...",Thread.CurrentThread.ManagedThreadId);
}
private static void ExecuteBackgroundThread()
{
var sw = Stopwatch.StartNew();
Console.WriteLine("Thread Id: {0}" + Environment.NewLine + "Thread State: {1}" + Environment.NewLine + "Priority {2}" + Environment.NewLine + "IsBackground {3}",
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.ThreadState,
Thread.CurrentThread.Priority,
Thread.CurrentThread.IsBackground);
do
{
Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
Thread.CurrentThread.ManagedThreadId,
sw.ElapsedMilliseconds / 1000.0);
Thread.Sleep(2000);
} while (sw.ElapsedMilliseconds <= 5000);
sw.Stop();
}

The following screenshot shows the output of the preceding code:

As you can see, the primary thread was created as a foreground thread while the worker thread was created as a background thread. When we stopped the primary thread, it stopped the background thread. This is why the elapsed time statement was not displayed through the loop, which is running for 5 seconds (while(sw.ElapsedMilliseconds <=5000)).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.52.7