top
April flash sale

Search

C# Tutorial

Multithreading is a method to implement concurrent programming where multiple threads operate simultaneously. Threads are lightweight processes that signify the execution path in a program. Thread usage increases the efficiency of an application and reduces the CPU cycle time wastage.The Thread Life CycleThe thread life cycle encapsulates the life of a thread. It starts when an object of System.Threading.Thread class is created and ends when thread has terminated. The thread states in the thread life cycle are given as follows:1. Unstarted StateWhen the instance of the thread has been created but the Start method has not been called, that is the unstarted state.2. Ready StateWhen the thread is ready to run, it is in the ready state. This thread is just waiting for the CPU cycle.3. Not runnable StateA thread can be in the not runnable state when the wait or sleep method has been called. This state can also occur if the thread is blocked because of I/O operations.4. Dead StateThe thread enters the dead state if it is aborted or if it has completed its execution.The Thread ClassThe System.Threading namespace provides the classes and interfaces that implement multithreaded programming. One of the classes in this namespace is the Thread class. This class is used for creating and controlling threads.Details about the constructors, properties and methods in Thread Class are given as follows:Constructors in Thread ClassThe different constructors and their description is given as follows:Table: Constructors in Thread Class in C#Source: MSDNConstructorsDescriptionThread(ParameterizedThreadStart)This constructor initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.Thread(ParameterizedThreadStart, Int32)This constructor initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread.Thread(ThreadStart)This constructor initializes a new instance of the Thread class.Thread(ThreadStart, Int32)This constructor initializes a new instance of the Thread class, specifying the maximum stack size for the thread.Properties in Thread ClassThe different properties and their description is given as follows:Table: Properties in Thread Class in C#Source: MSDNPropertiesDescriptionApartmentStateThis property gets or sets the apartment state of this thread.CurrentContextThis property gets the current context in which the thread is executing.CurrentCultureThis property gets or sets the culture for the current thread.CurrentPrincipalThis property gets or sets the thread's current principal (for role-based security).CurrentThreadThis property gets the currently running thread.CurrentUICultureThis property gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.ExecutionContextThis property gets an ExecutionContext object that contains information about the various contexts of the current thread.IsAliveThis property gets a value indicating the execution status of the current thread.IsBackgroundThis property gets or sets a value indicating whether or not a thread is a background thread.IsThreadPoolThreadThis property gets a value indicating whether or not a thread belongs to the managed thread pool.ManagedThreadIdThis property gets a unique identifier for the current managed thread.NameThis property gets or sets the name of the thread.PriorityThis property gets or sets a value indicating the scheduling priority of a thread.ThreadStateThis property gets a value containing the states of the current thread.Methods in Thread ClassThe different methods and their description is given as follows:Table: Methods in Thread Class in C#Source: MSDNMethodsDescriptionAbort()This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.BeginCriticalRegion()This method notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.BeginThreadAffinity()This method notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.EndCriticalRegion()This method notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.EndThreadAffinity()This method notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.Finalize()This method ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.GetDomain()This method returns the current domain in which the current thread is running.GetType()This method gets the Type of the current instance.Interrupt()This method interrupts a thread that is in the WaitSleepJoin thread state.MemoryBarrier()This method synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().Resume()This method resumes a thread that has been suspended.Sleep(Int32)This method suspends the current thread for the specified number of milliseconds.Start()This method causes the operating system to change the state of the current instance to Running.Suspend()This method either suspends the thread, or if the thread is already suspended, has no effectVolatileRead(Byte)This method reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.VolatileWrite(Byte, Byte)This method writes a value to a field immediately, so that the value is visible to all processors in the computer.Yield()This method causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield toCreate a ThreadTo create a Thread, simply use the Thread class:Source Code: Program to create a Thread in C#using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; class Example {    public void FirstThread()    {        for (int i = 0; i < 5; i++)        {            Console.WriteLine("My Thread");        }    } } class Sample {    public static void Main()    {        Example e = new Example();        Thread t = new Thread(new ThreadStart(e.FirstThread));        t.Start();        Console.Read();    } }The above program generates the following output:My Thread My Thread My Thread My Thread My ThreadThe Main ThreadThe Main Thread is the first thread that is created and executed inside a process. It is automatically created when the process starts execution.A program that demonstrates the Main thread is given as follows:Source Code: Program to implement Main Thread in C#using System; using System.Threading; namespace MultithreadingDemo {   class Example   {      static void Main(string[] args)      {         Thread myThread = Thread.CurrentThread;         myThread.Name = "Main_Thread";         Console.WriteLine("This thread is the {0}", myThread.Name);      }   } }The output of the above program is as follows:This thread is the Main_ThreadNow let us understand the above program.The CurrentThread property of the Thread class is used to access the Main thread. The name of the thread is specified is Main_Thread. After that, this is displayed. The code snippet for this is given as follows:    Thread myThread = Thread.CurrentThread;         myThread.Name = "Main_Thread";         Console.WriteLine("This thread is the {0}", myThread.Name);Check status of Current ThreadThe isAlive property is to be used if you want to check the status of current Thread in C#.Let us see an example:Source Code: Program to check the status of current Thread in C#using System; using System.Threading; namespace Example {    class MyThread    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "This is my first thread!";            Console.WriteLine("Status of current thread = {0}", t.IsAlive);            Console.ReadKey();        }    } }The above program generates the following output:Status of current thread = TrueGet the name of Current ThreadTo get the name of the current thread, you need to use the Name property of the Thread class. Let us see an example:Source Code: Program to get the name of current Thread in C#using System; using System.Threading; namespace Demo {    class MyClass    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "First Thread";            Console.WriteLine("Name of thread : {0}", t.Name);            Console.ReadKey();        }    } }The above program generates the following output:Name of thread : First ThreadDisplay the priority of the Current ThreadThe Priority property of the Thread class is to be used for displaying the priority of the Current Thread:Source Code: Program to display the priority of current Thread in C#using System; using System.Threading; namespace Example {    class MyThreadClass    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "First Thread";            Console.WriteLine("Thread Name : {0}", t.Name);            Console.WriteLine("Thread Priority : {0}", t.Priority);            Console.ReadKey();        }    } }The above program generates the following output:Thread Name : First Thread Thread Priority : NormalPause the Thread for a specified periodUse the Sleep() method to pause the Thread for a specified period. Let us see the code now:Source Code: Program to pause the Thread for a specified period in C#using System; using System.Threading; namespace Example {    class MyThreadClass    {        static void Main(string[] args)        {            Thread t = Thread.CurrentThread;            t.Name = "First Thread";            Console.WriteLine("Thread Name : {0}", t.Name);            Console.WriteLine("Thread Priority : {0}", t.Priority);            Console.WriteLine("Child Thread Paused...");            // using Sleep() method            Thread.Sleep(1000);            Console.WriteLine("Child Thread Resumed...");            Console.ReadKey();        }    } }The above program generates the following output:Thread Name : First Thread Thread Priority : Normal Child Thread Paused... Child Thread Resumed...
logo

C# Tutorial

Multithreading in C#

Multithreading is a method to implement concurrent programming where multiple threads operate simultaneously. Threads are lightweight processes that signify the execution path in a program. Thread usage increases the efficiency of an application and reduces the CPU cycle time wastage.

The Thread Life Cycle

The thread life cycle encapsulates the life of a thread. It starts when an object of System.Threading.Thread class is created and ends when thread has terminated. The thread states in the thread life cycle are given as follows:

1. Unstarted State

When the instance of the thread has been created but the Start method has not been called, that is the unstarted state.

2. Ready State

When the thread is ready to run, it is in the ready state. This thread is just waiting for the CPU cycle.

3. Not runnable State

A thread can be in the not runnable state when the wait or sleep method has been called. This state can also occur if the thread is blocked because of I/O operations.

4. Dead State

The thread enters the dead state if it is aborted or if it has completed its execution.

The Thread Class

The System.Threading namespace provides the classes and interfaces that implement multithreaded programming. One of the classes in this namespace is the Thread class. This class is used for creating and controlling threads.

Details about the constructors, properties and methods in Thread Class are given as follows:

Constructors in Thread Class

The different constructors and their description is given as follows:

Table: Constructors in Thread Class in C#

Source: MSDN

ConstructorsDescription
Thread(ParameterizedThreadStart)This constructor initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.
Thread(ParameterizedThreadStart, Int32)This constructor initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread.
Thread(ThreadStart)This constructor initializes a new instance of the Thread class.
Thread(ThreadStart, Int32)This constructor initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

Properties in Thread Class

The different properties and their description is given as follows:

Table: Properties in Thread Class in C#

Source: MSDN

PropertiesDescription
ApartmentStateThis property gets or sets the apartment state of this thread.
CurrentContextThis property gets the current context in which the thread is executing.
CurrentCultureThis property gets or sets the culture for the current thread.
CurrentPrincipalThis property gets or sets the thread's current principal (for role-based security).
CurrentThreadThis property gets the currently running thread.
CurrentUICultureThis property gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
ExecutionContextThis property gets an ExecutionContext object that contains information about the various contexts of the current thread.
IsAliveThis property gets a value indicating the execution status of the current thread.
IsBackgroundThis property gets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThreadThis property gets a value indicating whether or not a thread belongs to the managed thread pool.
ManagedThreadIdThis property gets a unique identifier for the current managed thread.
NameThis property gets or sets the name of the thread.
PriorityThis property gets or sets a value indicating the scheduling priority of a thread.
ThreadStateThis property gets a value containing the states of the current thread.

Methods in Thread Class

The different methods and their description is given as follows:

Table: Methods in Thread Class in C#

Source: MSDN

MethodsDescription
Abort()This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
BeginCriticalRegion()This method notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
BeginThreadAffinity()This method notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
EndCriticalRegion()This method notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
EndThreadAffinity()This method notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
Finalize()This method ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.
GetDomain()This method returns the current domain in which the current thread is running.
GetType()This method gets the Type of the current instance.
Interrupt()This method interrupts a thread that is in the WaitSleepJoin thread state.
MemoryBarrier()This method synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().
Resume()This method resumes a thread that has been suspended.
Sleep(Int32)This method suspends the current thread for the specified number of milliseconds.
Start()This method causes the operating system to change the state of the current instance to Running.
Suspend()This method either suspends the thread, or if the thread is already suspended, has no effect
VolatileRead(Byte)This method reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
VolatileWrite(Byte, Byte)This method writes a value to a field immediately, so that the value is visible to all processors in the computer.
Yield()This method causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to

Create a Thread

To create a Thread, simply use the Thread class:

Source Code: Program to create a Thread in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
class Example
{
   public void FirstThread()
   {
       for (int i = 0; i < 5; i++)
       {
           Console.WriteLine("My Thread");
       }
   }
}
class Sample
{
   public static void Main()
   {
       Example e = new Example();
       Thread t = new Thread(new ThreadStart(e.FirstThread));
       t.Start();
       Console.Read();
   }
}

The above program generates the following output:

My Thread
My Thread
My Thread
My Thread
My Thread

The Main Thread

The Main Thread is the first thread that is created and executed inside a process. It is automatically created when the process starts execution.

A program that demonstrates the Main thread is given as follows:

Source Code: Program to implement Main Thread in C#

using System;
using System.Threading;
namespace MultithreadingDemo
{
  class Example
  {
     static void Main(string[] args)
     {
        Thread myThread = Thread.CurrentThread;
        myThread.Name = "Main_Thread";
        Console.WriteLine("This thread is the {0}", myThread.Name);
     }
  }
}

The output of the above program is as follows:

This thread is the Main_Thread

Now let us understand the above program.

The CurrentThread property of the Thread class is used to access the Main thread. The name of the thread is specified is Main_Thread. After that, this is displayed. The code snippet for this is given as follows:

    Thread myThread = Thread.CurrentThread;
        myThread.Name = "Main_Thread";
        Console.WriteLine("This thread is the {0}", myThread.Name);

Check status of Current Thread

The isAlive property is to be used if you want to check the status of current Thread in C#.

Let us see an example:

Source Code: Program to check the status of current Thread in C#

using System;
using System.Threading;
namespace Example
{
   class MyThread
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "This is my first thread!";
           Console.WriteLine("Status of current thread = {0}", t.IsAlive);
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Status of current thread = True

Get the name of Current Thread

To get the name of the current thread, you need to use the Name property of the Thread class. Let us see an example:

Source Code: Program to get the name of current Thread in C#

using System;
using System.Threading;
namespace Demo
{
   class MyClass
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "First Thread";
           Console.WriteLine("Name of thread : {0}", t.Name);
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Name of thread : First Thread

Display the priority of the Current Thread

The Priority property of the Thread class is to be used for displaying the priority of the Current Thread:

Source Code: Program to display the priority of current Thread in C#

using System;
using System.Threading;
namespace Example
{
   class MyThreadClass
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "First Thread";
           Console.WriteLine("Thread Name : {0}", t.Name);
           Console.WriteLine("Thread Priority : {0}", t.Priority);
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Thread Name : First Thread
Thread Priority : Normal

Pause the Thread for a specified period

Use the Sleep() method to pause the Thread for a specified period. Let us see the code now:

Source Code: Program to pause the Thread for a specified period in C#

using System;
using System.Threading;
namespace Example
{
   class MyThreadClass
   {
       static void Main(string[] args)
       {
           Thread t = Thread.CurrentThread;
           t.Name = "First Thread";
           Console.WriteLine("Thread Name : {0}", t.Name);
           Console.WriteLine("Thread Priority : {0}", t.Priority);
           Console.WriteLine("Child Thread Paused...");
           // using Sleep() method
           Thread.Sleep(1000);
           Console.WriteLine("Child Thread Resumed...");
           Console.ReadKey();
       }
   }
}

The above program generates the following output:

Thread Name : First Thread
Thread Priority : Normal
Child Thread Paused...
Child Thread Resumed...

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial