Sponsored Ad

Wednesday, June 2, 2010

How to run a thread in BackGround in C#

How to run a thread in BackGround in C#

Threads either run in background or foreground. There is a property by which one can know thred running status.

Thread.CurrentThread.IsBackground

One can force thread to run in background or forground by setting the property

thread1.IsBackground = true; //thread will run in background

thread1.IsBackground = false; //thread will run in foreground

like in current example the new thread is running in background and the parent thread is running in foreground.

 

How to run a thread in BackGround in C# Example:

using System;
using System.Text;
using System.Threading;

namespace Console_App
{

    public class Class1
    {
        public void fun1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" #" + i + "Running in Background: " + Thread.CurrentThread.IsBackground );            
            }
        }
    }
    public class Class2
    {
        public static void Main()
        {
            Class1 a = new Class1();
            Thread thread1 = new Thread(new ThreadStart(a.fun1));
            Console.WriteLine("Before Starting Thread - Running in Background: " + Thread.CurrentThread.IsBackground);
            thread1.Start();
            thread1.IsBackground = true;
            Console.WriteLine("After Staring Thread  - Running in Background: " + Thread.CurrentThread.IsBackground);           
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment

Sponsored Ad

Development Updates