Wednesday 15 May 2013

Background and Foreground thread in c# ?




  • 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.
    Example:
    Thread Foreground Background






    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace TestThread
    {
    class Program
    {
    static void Main(string[] args)
    {

    //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
    t1.Start(true);

    //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
    t2.Start();

    Console.ReadKey();
    }

    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);
    }
    }

    }
    }

    0 comments:

    Post a Comment