Threading in c#

By
C# supports the concept of Multithreading which helps to execute two or more  "parts" of a program currently.Every part is known as a thread.A thread is a separate sequence of instructions for  executing a specific task in the program. Multithreading means,performing multiple tasks at the same time during the execution of a program.Every c# program starts the execution with a single thread which is called main thread .The Main thread is runned by the (CLR) & operating system.
          The process of developing a program for execution with multiple threads , is called multithreading programming and the process of  execution is called multithreading.
There are some advantage of threading in c#.
  • Optimize the use of computer resources such as memory i/o device.
  • Minimize the time
The Namespace for multithreading is 'System.Threading' in c#,that containing classes and interfaces that are required for developing and running multithreaded application.We can use the methods and properties contained in these classes to perform task such as synchronising the activities of a thread and creating a thread.
You can easily make any Online Applications with the help of Multithreading and Database.
There are some important classes in the 'system.threading Namespace.
  1. Thread
  2. ThreadPool
  3. Monitor
  4. Mutex
 1. ) Thread Class
  The Thread class is used to perform tasks such as creating and setting the priority a thread.We can use this class to obtained its status and a thread.
There are some important properties of thread class which are given below:
  • Name:-It is used to specify a name for a thread.
  • Priority:-It obtain a value which indicate the scheduling the scheduling priority of a thread.
  • Normal:- This value must be scheduled after the threads with Above Normal priority but before the Below Normal priority threads.
  • Highest:-The Highest value indicates that thread must be scheduled for running before any other threads.
  • Above Normal:-The Above Normal value indicates that the thread with this value must be scheduled after highest priority threads but before the Normal Priority thread.
  • Below Normal:-This value indicates that the thread with this value must be scheduled after a Normal Priority value thread but before the Lowest priority thread.
  • Lowest:- This value indicates that the thread with  this value must be scheduled for running after the threads with other priorities such as Normal and Highest.
  • Thread State:-By default ,the value of the thread state properties is unstarted.
There are some,Thread state value which are given below:
  1. Running:- This Value indicates that the current thread is running.
  2. Stopped:-This value indicates that the current thread is stopped.
  3. Suspended:- This value indicates that the current thread is suspended.
  4. Unstarted:- This value indicates that the thread has not been started yet using the start method of the thread class.
  5. Waitsleepjoin:-The value indicates that the current thread is blocked because of call to wait,sleep or join method.
  • IsThreadpoolthread:-This value indicates whether a thread is part of a thread pool or not. The value of IsThreadPoolThread properties is true if the thread is part of a thread pool,otherwise,it is false.
  • To retrieve the name of the thread,which is currently running.
  • IsAlive:- This value indicate the current state of thread execution . The value of IsAlive property is true if the thread has been started otherwise it is false.
There are some methods of the thread class also which provides certain methods that can be used to manage operation such as starting  thread and resuming a suspended thread which is given below:
  • start:-It is used for starting a thread.
  • Suspend:-It is used ,for suspending a thread.
  • Join:- Block a thread until another thread has terminated.
  • Resume:-It is  used for resuming a thread which has been suspended earlier.
  • Interrupt:-It is used to interrupt the thread,which is in the waitsleepjoin state.
  • SpinWait:- It is used to make  a thread wait the number of times specified in Iteration parameter.
  • Abort:-It is used to terminate the thread as soon as possible.
  • Interrupt:-It is used to interrupts the current thread from a suitable wait period.
2. ) ThreadPool class:-
This class provides a pool of threads that helps to perform tasks such as processing of asynchronous i/o and waiting on behalf of another thread. 
There are some important methods of ThreadPool class which are given below:
  • GetType:- It is used to obtain the type for the current thread pool.
  • Equals:- It is used to determine whether two thread pool are equal or not.
  • SetMaxThreads:-It is used ,to specify the number of requests to the ThreadPool that can be concurrently active.
  • SetMinThreads:-It is used to specify the number of idle threads that can be maintained by a thread pool for new requests.
  • QueueuserWorkItem:-It allows a method to be queued for execution.
3. ) Monitor class:-
This class provides control access to an object by granting a lock for the object to a single thread.When an object is locked for a thread then the access to a specific program code is restricted.
There are some important methods that allow to perform task such as acquiring and releasing a lock for an object,which are given below:
  • GetType:- It is used to allow to obtain the type for the current instance of the monitor class.
  • Enter:-It is used to allow a thread to obtain a lock on a specified object.
  • TryEnter:-It is used to allow a thread to try and obtain a lock on a specified object.
  • Wait:-It is used to allow  thread to release the lock on a object and block the thread for the time period until which it again obtains the lock.
  • Exit:-It is used to allow a thread to release a lock on  specified object.
4. ) Mutex class:
A mutex is basically used for synchronistion.It helps to perform interprocess synchronisation in c#.Mutex allows a thread to have exclusive access to shared resources when a thread to have exclusive access to shared resources .When a thread obtains a mutex,another thread,which wants to obtained the mutex,is suspended until the first thread relese the mutex.
There are some important methods in mutex class which are given below:
  • Equals:-It is used ,to determine whether two mutex are equal are not.
  • SetAccessControl:- It is used, to set the access control security for a specified mutex.
  • ReleaseMutex:-It is used to release a mutex once.
  • OpenExisting:- It is used to open an existing mutex.
  • cl0se:- It is used to release the resources held by an object of the wait handle class.
Note:-The mutex class provides the handle and safe wait handle properties that can be used to retrieve the handle for the operating system.

Examples:
1. ) Creating and starting the threads:-
    using System;
    using System.Threading;
    namespace threading
    {
        class student
        {
            public void thread1()
            {
                Console.WriteLine("First thread of student class and method thread1 is running");
                Thread.Sleep(1000);
                Console.WriteLine("First thread of student class and method thread1 has ended");
            }
            public void thread2()
            {
                Console.WriteLine("Second thread of student class and method thread2 is running");
                Thread.Sleep(2000);A
                Console.WriteLine("Second thread of student class and method thread2 has ended");
            }
           public static void Main(string[] args)
            {
                student st = new student();
                Thread T1 = new Thread(new ThreadStart(st.thread1));  //creating thread T1 
                T1.Start();         // Starting thread T1
                Console.WriteLine("First thread T1 started");
                Thread T2 = new Thread(new ThreadStart(st.thread2));  //creating thread T2 
                T2.Start();         // Starting thread T2
                Console.WriteLine("second thread T2 started");
                Console.ReadLine();
            }
        }
    }
    
output:-
create thread

2. ) Creating a thread with timer:-
using System;
using System.Timers; 
namespace timerthread
{
    class student
    {
        public void show(object TIME)
        {
            Console.WriteLine(TIME);
        }
        static void Main(string[] args)
        {
            Timer time = new Timer();
            time.Interval = 2000;
            time.Elapsed += new ElapsedEventHandler(time_Elapsed);
            time.Start();
            Console.ReadLine();
            time.Stop();
            Console.WriteLine("Timer thread stopped");
            Console.ReadLine();
            time.Start();
            Console.WriteLine("Thread destroyed");
            time.Dispose();
        }
        static void time_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Timer is passing by:");
            Console.WriteLine(DateTime.Now);
        }
    }
}
Output:-
timer thread

scheduling a Thread:-
The threads can be scheduled by setting the priority of the thread using the priority property of the thread class.There are some priority of thread class which are given below:
  • Highest
  • AboveNormal
  • Normal
  • Below Normal
  • Lowest
Example:-
using System;
using System.Threading;
namespace priority_thread
{
    class student
    {
        public void T1()
        {
            Console.WriteLine("Thread T1");
            Console.WriteLine("priority of thread T1 is: " +Thread.CurrentThread.Priority.ToString());
            Thread.Sleep(5000);
            Console.WriteLine("thread with " + Thread.CurrentThread.Priority.ToString() + " has runned");

        }
        public void T2()
        {
            Console.WriteLine("Thread T2");
            Console.WriteLine("priority of thread T2 is: " + Thread.CurrentThread.Priority.ToString());
            Thread.Sleep(6000);
            Console.WriteLine("thread with " + Thread.CurrentThread.Priority.ToString() + " has runned");

        }
        public void T3()
        {
            Console.WriteLine("Thread T3");
            Console.WriteLine("priority of thread T3 is: " + Thread.CurrentThread.Priority.ToString());
            Thread.Sleep(7000);
            Console.WriteLine("thread with " + Thread.CurrentThread.Priority.ToString() + " has runned");

        }
        public void T4()
        {
            Console.WriteLine("Thread T4");
            Console.WriteLine("priority of thread T4 is: " + Thread.CurrentThread.Priority.ToString());
            Thread.Sleep(8000);
            Console.WriteLine("Thread with " + Thread.CurrentThread.Priority.ToString() + " has runned");
            Console.WriteLine(" ");
        }
        static void Main(string[] args)
        {
            Console.WriteLine("........thread is scheduling.............");
            student st = new student();
            Thread t1 = new Thread(new ThreadStart(st.T1));
            Thread t2 = new Thread(new ThreadStart(st.T2));
            Thread t3 = new Thread(new ThreadStart(st.T3));
            Thread t4 = new Thread(new ThreadStart(st.T4));
            Console.WriteLine("priority of main thread is:" + Thread.CurrentThread.Priority.ToString());
            Console.WriteLine(" ");
            t1.Name = "Thread T1";
            t2.Name = "Thread T2";
            t3.Name = "Thread T3";
            t4.Name = "Thread T4";
            t1.Priority = ThreadPriority.AboveNormal;
            t2.Priority = ThreadPriority.BelowNormal;
            t3.Priority = ThreadPriority.Lowest;
            t4.Priority = ThreadPriority.Highest;
            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            Console.ReadLine();
        }
    }
}
output:-
priority threads

Synchronising Threads:-
The Thread can be synchronised by using methods such as sleep and join of the thread class.
Example of ThreadPool:-
using System;
using System.Threading;
namespace Poolthread
{
    class student
    {
       static object newthread = new object();
       static int i = 10;
        public static void Main(string[] args)
        {
            for (int j = 0; j < i; j++)
            {
                ThreadPool.UnsafeQueueUserWorkItem(show, j);
            }
   Console.WriteLine("10 threads are running one by one and stop after 5 second");
            lock (newthread)
            {
                if (i > 0)
                    Monitor.Wait(newthread);
            }
            Console.WriteLine("Threads are stopped successfully");
            Console.ReadLine();
        }
          public static void show(object newobj)
          {
              Console.WriteLine("Thread started:"+newobj);
              Thread.Sleep(5000);
              Console.WriteLine("Thread ended:"+newobj);
              lock(newthread)
              {
                  Monitor.Pulse(newthread);
              }
          }
        }
    }
Output:-
poolthreads

Example of Lock keyword:-
using System;
using System.Threading;

namespace Lock_Keyword
{
    class useoflock
    {
        private object lockobj = new object();
        public void display()
        {
            Console.WriteLine("thread starting:" + Thread.CurrentThread.Name.ToString());
            int a = 5, b = 10;
            int mult = 0;
            lock (lockobj)
            {
                mult = a * b;
                Console.WriteLine(mult);
            }
            Thread.Sleep(600);
            Console.WriteLine(Thread.CurrentThread.Name.ToString()+"is stopped");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            useoflock ulock = new useoflock();
            Thread t1 =new Thread(new ThreadStart(ulock.display));
            Thread t2 =new Thread(new ThreadStart(ulock.display));
            Thread t3 = new Thread(new ThreadStart(ulock.display));
            t1.Name = "Thread1";
            t2.Name = "Thread2";
            t3.Name = "Thread2";
            t1.Start();
            t2.Start();
            t3.Start();
            Console.ReadLine();
        }
    }
}
Output:-
lock keyword

Example of Mutex:-
using System;
using System.Threading;

class Mutex1
{
   
    private static Mutex mutobj = new Mutex();   // Create a new Mutex 
    static int iteration = 2;
     static int threads = 3;

    public static void Main()
    {
        // Creating threads  
        for(int i = 0; i < threads; i++)
        {
            Thread th = new Thread(new ThreadStart(singleThread));
            th.Name = String.Format("Thread{0}", i + 1);
            th.Start();
        }
        Console.ReadLine();
    }

    private static void singleThread()
    {
        for(int i = 0; i < iteration; i++)
        {
            UseResource();
        }
    }
    private static void UseResource()
    {
        mutobj.WaitOne();
     Console.WriteLine("{0} has entered the safed area",Thread.CurrentThread.Name);
        Thread.Sleep(600);
     Console.WriteLine("{0} is leaving the safed area ",Thread.CurrentThread.Name);
        mutobj.ReleaseMutex(); // Release the Mutex.
    }
}
Output:-
mutex

Description:- In above example ,all three thread follow the mutual exclusion.Means at one time only one thread will enter the critical section(safed area),which is shown in above example.

Types of Thread:-
  1. Foreground thread
  2. Background thread
Example of sequential execution of program:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sequential_execution
{
    class student
    {
        public void fun1()
        {
            for (int i = 0; i <= 3; i++) 
            {
                Console.WriteLine("function1 is executing");
            }

        }
         public void fun2()
        {
            for (int j = 0; j <= 3; j++)
            {
                Console.WriteLine("function2 is executing");
            }
        }
        
        static void Main(string[] args)
        {
            student st=new student();
            st.fun1();
            st.fun2();
            Console.ReadKey();
        }
    }
}
Output:-
sequential exequation

Description:-
In above example ,first function 1 runs and after that function 2 runs.It is known as synchronous processing or sequential processing.Now in Next program,I will show you how to implement  threading in this program using c#.In Multithreading each function(thread) runs parally.In other word parallel execution of program is known as multithreading.

Example of Parallel Execution of program:-
Ex.
using System;
using System.Threading;
namespace parallel_execution
{
    class Program
    {
        public static void fun1()
        {
            for (int i = 0; i <= 2; i++) 
            {
                Console.WriteLine("function1 is executing " + i.ToString());
                Thread.Sleep(3000); //wait 3 second  
            }

        }
         public static void fun2()
        {
            for (int j = 0; j <= 3; j++)
            {
                Console.WriteLine("function2 is executing "+j.ToString());
                Thread.Sleep(3000);  //wait 3 second
            }
         }
         public static void fun3()
         {
             for (int k = 0; k<= 4; k++)
             {
                 Console.WriteLine("function3 is executing " + k.ToString());
                 Thread.Sleep(3000);  //wait 3 second
             }
         }
        static void Main(string[] args)
        {
            Thread obj1 = new Thread(fun1);//second thread created
            Thread obj2 = new Thread(fun2);//second thread created
            Thread obj3 = new Thread(fun3);//second thread created
            obj1.Start(); //invoke first thread
            obj2.Start(); //invoke second thread
            obj3.Start(); //invoke third thread
            Console.ReadKey();
        }
    }
}
Output:
parallel execution

Description:-Above program executes the parally manner.In this computer processor gives the time slot to execute the each program.
1.) Foreground Thread:-
Foreground thread are those thread even main application is exited but it continue running whenever foreground thread is not stopped.
using System;
using System.Threading;
namespace Foreground_thread
{
    class Program
    {
        public static void function1()
        {
            Console.WriteLine("function1 is running");
            Console.ReadLine(); //wait for input
            Console.WriteLine("function1 is exited");
        }
        static void Main(string[] args)
        {
            Thread obj1 = new Thread(function1);
            obj1.Start();
            Console.WriteLine("The main application has exited");
            Console.ReadLine();
        }
    }
}

Output:-
foreground

Description:-
In above example if we run the program then it show that "The main application has exited" but one thread is running which is known as foreground thread. after putting the input ,it shows "function1 is exited".it is follow the definition of foreground thread.

2.) Background Thread:-
A Background thread is die off if the main application is finished.
Ex.
using System;
using System.Threading;
namespace Background_thread
{
    class Program
    {
        public static void function1()
        {
            Console.WriteLine("function1 is running.......");
            Console.ReadLine(); //wait for input
            Console.WriteLine("function1 is exited");      
        }
        static void Main(string[] args)
        {
            Thread obj1 = new Thread(function1);
            obj1.IsBackground = true;
            obj1.Start();
            Console.WriteLine("The main application has exited");
            Console.ReadLine(); 
        }
    }
}
Output:-
Background

Description:-
In above example ,if we run the application,its showing"The main application has exited".if main thread is exited then background thread is also exited.Which is shown in above examples.
Note:-For above example you can cover many things like:
  • No need for c sharp training.
  • Use of Database in Threading.
  • Make Online Application.
  • Scheduling
For More:-
  1. Send mail from aps.net application free
  2. Create setup file with database
  3. Binding Navigator control
  4. File handling Real Application
  5. Directory and Directory info class
  6. .Net Interview Questions & Answers

To Get the Latest  Free Updates Subscribe
Download whole Application from Below:-
                 Download

0 comments:

Post a Comment

Powered by Blogger.