Background and foreground thread in c#

Author posted by Jitendra on Posted on under category Categories c# and tagged as Tags with 1 Comment on Background and foreground thread in c#

Example of Threading in C#. Includes Foreground and Background Threading.

  • Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.
  • Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.
  • It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the Thread.Start() method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require.


    Thread Foreground Background
    Threading in CSharp
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace TestThread
    class Program
    static void Main(string[] args)
    Program obj = new Program();
    //Create object of parameterized thread, so that you can pass parameter to any thread
    ParameterizedThreadStart pst = new ParameterizedThreadStart(obj.function1);
    //Bydefault threads are Foreground Thread
    Thread t1 = new Thread(pst);
    //Set Thread Name
    t1.Name = "Thread1";
    //Passs Parameter to thread
    //Create object of ThreadStart, it does not have any parameter
    ThreadStart ts = new ThreadStart(obj.function2);
    Thread t2 = new Thread(ts);
    t2.Name = "Thread2";
    //Make it Background Thread
    t2.IsBackground = true;
    //Run the thread
    public void function1(object val)
    for (int i = 0; i < 5; i++)
    Console.WriteLine("This is parameterized function1 by {0} and Value passed is {1} ", Thread.CurrentThread.Name, val);
    public void function2()
    for (int i = 0; i < 5; i++)
    Console.WriteLine("This is function2 by : " + Thread.CurrentThread.Name);
    public void printInfo()
    System.Text.StringBuilder sb = new StringBuilder();
    sb.Append("            read Demo by ShivaSoft                     n");

    Related posts

    One thought on “Background and foreground thread in c#”

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.