We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Sunday, March 29, 2015

Threading In C#


Thread

A thread is a separate sequence of instructions for  executing a specific task in the program.

Main Thread

Every c# program starts the execution with a single thread which is called main thread .The Main thread is run by the (CLR) & operating system.

Multithreading 

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. Multithreading means,performing multiple tasks at the same time during the execution of a program.
          The process of developing a program for execution with multiple threads , is called multithreading programming and the process of  execution is called multithreading.

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 synchronizing the activities of a thread and creating a thread.

Important classes in the 'system.threading Namespace.
  1. Thread
  2. ThreadPool
  3. Monitor
  4. Mutex
 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.
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 IsAliveproperty 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.
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. 


Important methods of Thread Pool 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.
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.

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.
Mutex class
A mutex is basically used for synchronization. It helps to perform inter process synchronization 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.

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.
  • Close:-It is used to close an existing mutex.
    Thread Life Cycle 
    The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
    Following are the various states in the life cycle of a thread:
    • The Unstarted State: It is the situation when the instance of the thread is created but the Start method is not called.
    • The Ready State: It is the situation when the thread is ready to run and waiting CPU cycle.
    • The Not Runnable State: A thread is not executable, when:
      • Sleep method has been called
      • Wait method has been called
      • Blocked by I/O operations
    • The Dead State: It is the situation when the thread completes execution or is aborted.
    The Main Thread
    In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread.
    When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class.
    The following program demonstrates main thread execution:
     using System;using System.Threading;
      namespace CSharpExample
    {
          public class MainThreadProgram      {
                    static void Main(string[] args)
                    {
                          Thread th = Thread.CurrentThread;
                          th.Name = "MainThread";
                          Console.WriteLine("This is {0}", th.Name); Console.ReadLine();
                    }
              }
}

Output:
This is MainThread
  • It is used to release the resources held by an object of the wait handle class.

Creating Thread
Threads are created by extending the Thread class. The extended Thread class then calls the Start() method to begin the child thread execution.
The following program demonstrates the concept:
using System;
using System.Threading;

namespace CSharpExample
{
      class ThreadCreationProgram
      {
            public static void CallToChildThread()
            {
                  Console.WriteLine("Child thread starts");
            }
            static void Main(string[] args)
            {
                  ThreadStart childref = new ThreadStart(CallToChildThread);
                  Console.WriteLine("In Main: Creating the Child thread");
                  Thread childThread = new Thread(childref);
                  childThread.Start();
                  Console.ReadLine();
            }
      }
}
Output:
In Main: Creating the Child thread Child thread starts

Managing Threads
The Thread class provides various methods for managing threads.
The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of time.

      namespace MultithreadingApplication
      {
            class ThreadCreationProgram
            {
                  public static void CallToChildThread()
                  {
                        Console.WriteLine("Child thread starts");
                        int sleepfor = 5000;
                        Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
                        Thread.Sleep(sleepfor); Console.WriteLine("Child thread resumes");
                  }
                  static void Main(string[] args)
                  {
                        ThreadStart childref = new ThreadStart(CallToChildThread);
                        Console.WriteLine("In Main: Creating the Child thread");
                        Thread childThread = new Thread(childref);
                        childThread.Start();
                        Console.ReadLine();
                  }
            }
      }

Output
In Main: Creating the Child thread Child thread starts Child Thread Paused for 5 seconds Child thread resumes.

Destroying Threads
The Abort() method is used for destroying threads.
The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught, the control is sent to the finally block, if any.
The following program illustrates this:
class ThreadCreationProgram
      {
            public static void CallToChildThread()
            {
                  try
                  {
                        Console.WriteLine("Child thread starts");
                        for (int counter = 0; counter <= 10; counter++)
                        {
                              Thread.Sleep(500);
                              Console.WriteLine(counter);
                        }
                        Console.WriteLine("Child Thread Completed");
                  }
                  catch (ThreadAbortException e)
                  {
                        Console.WriteLine("Thread Abort Exception");
                  }
                  finally
                  {
                        Console.WriteLine("Couldn't catch the Thread Exception");
                  }
            }
            static void Main(string[] args)
            {
                  ThreadStart childref = new ThreadStart(CallToChildThread);
                  Console.WriteLine("In Main: Creating the Child thread");
                  Thread childThread = new Thread(childref); childThread.Start();
                  Console.WriteLine("In Main: Aborting the Child thread");
                  childThread.Abort();
                  Console.ReadLine();
            }
      }
Output
In Main: Creating the Child thread Child thread starts 0 1 2 In Main: Aborting the Child thread Thread Abort Exception Couldn't catch the Thread Exception.
Most Common Instance Member of the System.Threading.Thread class
The following are the most common instance members of the System.Threading.Thread class:
  • Name 

    A property of string type used to get/set the friendly name of the thread instance.
     
  • Priority 

    A property of type System.Threading.ThreadPriority to schedule the priority of threads.
     
  • IsAlive 

    A Boolean property indicating whether the thread is alive or terminated.
     
  • ThreadState 

    A property of type System.Threading.ThreadState, used to get the value containing the state of the thread.
     
  • Start()Starts the execution of the thread.
     
  • Abort() 

    Allows the current thread to stop the execution of the thread permanently.
     
  • Suspend() 

    Pauses the execution of the thread temporarily.
     
  • Resume() Resumes the execution of a suspended thread.
     
  • Join() 

    Make the current thread wait for another thread to finish.


1. ) What is thread?

A thread is basically a separate sequence of instruction designed to performing a " specific task" in the program.

2. ) What is Multithreading in c# ?

Performing multiple task at same time during the execution of a program,is known as multithreading.

3. ) What is the Namespace used for multithreading in c# ?

using System.Threading;

4. ) What are the advantage of multithreading in c# ?

There are two main advantage to use of multithreading in c#.
Optimize the use of computer resources such as memory.
Save time

5. ) What are the classes used in System.Threading Namespace ?

Thread
Thread Pool
Monitor
Mutex

6. ) What is the use of Thread class in c#?

The Thread class is used to perform tasks such as creating and setting the priority of a thread.

7. ) What are the main properties of thread class?

Priority
Thread State
IsAlive
Current thread
Name etc.

8. ) What are the methods used in thread class?

Join
Resume
sleep
Spin Wait
Suspended
Start
Interrupt

9. ) What is the Thread Pool class in c#?

The Thread Pool class is used,to perform task such as processing of asynchronous i/o and waiting on behalf of another thread.

10. ) What are the method used in Thread Pool class ?

Gettype
Equals
SetMaxThreads
QueueUserWorkItem

11. ) What is monitor class in c# ?

The Monitor class is used to access an object by granting a lock for the object to a single thread.

12. ) What are the methods used in monitor class ?

Enter
Exit
TryEnter
Wait
GetType

13. ) What is Mutex class in c# ?

A Mutex is used ,to perform interprocess synchronization and a thread to have exclusive access to shared resources.

14. ) What are the methods used in Mutex class ?

Equals
close
OpenExisting
SetAccessControl
Release Mutex

15. ) What are the syntax for creating and starting a thread in c# ?

First define a delegate:-
Public delegate void start_thread();
Create a new thread:-
Thread thread_name = new Thread(new start_thread(method_name));

16. ) Can we create timer in threading ?

Yes.

17. ) How can we scheduled a thread in c# ?

We can scheduled the thread with the help of priority property of the Thread class.

18. ) What are the priority value used for scheduling a thread in c# ?

Highest
Normal
AboveNormal
BelowNormal
Lowest

19. ) What are the two types of thread in c# ?

Foreground thread
Background thread

14 comments:

Unknown said...

I am really happy to say it’s an interesting post to read. I learn new information from your blog; you are doing a great job. Keep it up.

BULK SMS SERVICE FOR REAL ESTATE
BULK SMS IN KUWAIT
bulk sms india

Unknown said...

Carry on, don’t stop. Very nice, I really like your blog… Keep it up.

bulk sms service provider in laxmi nagar

Unknown said...

Thanks for the informative blog, Needed it! You did a great job. Seems like you know a lot about this topic. Thankyou for this interesting information.

bulk sms service provider in delhi

bulk sms service provider in laxmi nagar

Bulk sms service provider in india

Unknown said...

The blog you write is really impressive, this is one of the best desription I have read on this topic. Seems like you know a lot about this topic. Thankyou for this interesting information.
VISIT:
digital marketing company in delhi

digital marketing agency in delhi

digital marketing companies in delhi

Tanu Nashkar said...

Thanks for this helpful blog, but if you are one of them who suffer from hair issues like weak hair or thin hair, So now don't have to worry. Kinsley Extenso manufactures top Hair extensions at a reasonable price. It manufactures the different type of products like Tape Hair Extension, Human hair wig and Hair Volumizer

Dream Care India said...

Thanks for sharing such an valuable article. Also visit our website Dream Care India for the best Washing Machine Cover IFB in delhi ncr.

Dream Care India said...



Thanks for sharing such an valuable article.


freeze cover

Dream Care India said...

This is really helpful. You’re doing a great job, Keep it up

freeze cover

Kinsley Extenso said...

This is really helpful. You’re doing a great job, Keep it up
Hair extensions

Kinsley Extenso said...

This is really helpful. You’re doing a great job, Keep it up


Clip on Extensions

Kinsley Extenso said...

Really Nice Article & Thanks for sharing.

Permanent hair extensions

Hair extensions

Best hair extensions

Top hair extensions

Hair Wigs

Human Hair Extensions

Clip on Extensions

Real hair extensions

Buy hair extensions online

hair extensions near me

Keratin Hair Extensions

Kinsley Extenso said...

This is really helpful. You’re doing a great job, Keep it up
Human hair extensions in delhi

Permanent hair extensions

hair extensions shop near me

Human hair suppliers in delhi

Hair extension prices

Hair extensions cost in delhi

Wigs for Women

Human Hair manufacturers in delhi

Hair Extension in Mumbai

Humar Hair Wig

Hair Extension Salon

Digital marketing said...

thanks to giving your information .if you buy a
table cover design Click on link.

Educated Healing said...


Nice your Blog

Massive Male Plus UPDATE 2020 – Does It Really Work?

https://k12.instructure.com/eportfolios/7387/Home/Massive_Male_Plus_UPDATE_2020__Does_It_Really_Work
https://angel.co/company/massive-male-plus-male-enhancement-1
https://www.xfactory.io/forum/she-qun-huo-dong-community-events/massive-male-plus-update-2020-does-it-really-work
https://in.pinterest.com/pin/811633164091918022/
https://in.pinterest.com/pin/811633164091918048/
https://pubhtml5.com/otro/nizh
https://pubhtml5.com/otro/khwn
https://www.completefoods.co/diy/recipes/massive-male-plus-male-enhancement-5
https://www.emailmeform.com/builder/form/759OeBd7SJf5t7i1