Tuesday 12 September 2017

Multithreading in C#





Foregrounddthread which will continue to run after the main application exit.
BackgroundThread will be exited after the main application exit


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("mainfun enterted");
            Thread obj1 = new Thread(Function1);
            obj1.IsBackground = true;
            obj1.Start();
            //Thread obj2 = new Thread(Function2);
            Console.WriteLine("mainfun exited");
            //obj1.Start();
            //obj2.Start();
            //Console.ReadLine();
        }

        public static void Function1()
        {
            Console.WriteLine("Fun1 enterted");
            //for (int i = 0; i < 10; i++)
            //{
            //    Console.WriteLine("Function 1 : "+ i);
            //    Thread.Sleep(40);
            //}
            Console.ReadLine();
            Console.WriteLine("Fun1 exited");
        }

        public static void Function2()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Function 2 : " + i);
                Thread.Sleep(4000);
            }
        }
    }
}

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0