
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialMultithreading 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 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:
When the instance of the thread has been created but the Start method has not been called, that is the unstarted state.
When the thread is ready to run, it is in the ready state. This thread is just waiting for the CPU cycle.
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.
The thread enters the dead state if it is aborted or if it has completed its execution.
Multithreading in C# involves running multiple threads concurrently within a single program, enhancing performance and efficiency. Here are the key components:
System.Threading namespace provides classes and methods to create and manage threadsThread class, where each thread executes a separate path of codeThread.Start method initiates a thread's executionExample:
Thread thread = new Thread(new ThreadStart(TaskMethod));
thread.Start();
Multithreading in C# is beneficial when tasks are independent and can run concurrently, such as in
Consider an example of web server, when a web server receives multiple HTTP requests simultaneously, it can use multithreading to handle each request in a separate thread. This ensures that a slow request (e.g., a request that requires a database query) does not block other requests
Using multithreading in C# can significantly improve application performance and user experience
How to Use Multithreading:
To implement multithreading, start by creating a new thread using the Thread class from the System.Threading namespace. Define the task to be executed in a method and pass this method as a ThreadStart delegate to the Thread constructor. Invoke the Start method to run the thread. For example, Thread thread = new Thread(new ThreadStart(TaskMethod)); thread.Start();. Advanced methods include using the Task Parallel Library (TPL) and async and await keywords for simpler and more efficient multithreading management. Always ensure proper synchronization to avoid race conditions and deadlocks. Multithreading in C# should be used judiciously, keeping in mind the complexity it introduces to debugging and maintenance.
Steps to use Multithreading in C#
1. Creating a Thread:
Thread thread = new Thread(new ThreadStart(TaskMethod));
thread.Start();
2. Using Task Parallel Library (TPL):
Task.Run(() => TaskMethod());
3. Async/Await for Asynchronous Programming:
async Task MethodAsync() {
await Task.Run(() => TaskMethod());
}
Regular testing and profiling are essential to identify and resolve issues in multithreaded applications..
Here's a simple example demonstrating multithreading in C#:
using System;
using System.Threading;
class Program {
static void Main() {
Thread thread1 = new Thread(PrintNumbers);
Thread thread2 = new Thread(PrintNumbers);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
static void PrintNumbers() {
for (int i = 0; i < 5; i++) {
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: {i}");
Thread.Sleep(500); // Simulate work
}
}
}
Explanation:
This example shows how two threads execute the same method concurrently, improving performance.
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:
The different constructors and their description is given as follows:
Constructors | Description |
|---|---|
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. |
Table: Constructors in Thread Class in C#
Source: MSDN
The different properties and their description is given as follows:
Properties | Description |
|---|---|
ApartmentState | This property gets or sets the apartment state of this thread. |
CurrentContext | This property gets the current context in which the thread is executing. |
CurrentCulture | This property gets or sets the culture for the current thread. |
CurrentPrincipal | This property gets or sets the thread's current principal (for role-based security). |
CurrentThread | This property gets the currently running thread. |
CurrentUICulture | This property gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time. |
ExecutionContext | This property gets an ExecutionContext object that contains information about the various contexts of the current thread. |
IsAlive | This property gets a value indicating the execution status of the current thread. |
IsBackground | This property gets or sets a value indicating whether or not a thread is a background thread. |
IsThreadPoolThread | This property gets a value indicating whether or not a thread belongs to the managed thread pool. |
ManagedThreadId | This property gets a unique identifier for the current managed thread. |
Name | This property gets or sets the name of the thread. |
Priority | This property gets or sets a value indicating the scheduling priority of a thread. |
ThreadState | This property gets a value containing the states of the current thread. |
Table: Properties in Thread Class in C#
Source: MSDN
The different methods and their description is given as follows:
Methods | Description |
|---|---|
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 |
Table: Methods in Thread Class in C#
Source: MSDN
To create a Thread, simply use the Thread class:
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();
}
}
Source Code: Program to create a Thread in C#
The above program generates the following output:
My Thread
My Thread
My Thread
My Thread
My 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:
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);
}
}
}
Source Code: Program to implement Main Thread in C#
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);
The isAlive property is to be used if you want to check the status of current Thread in C#.
Let us see an example:
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();
}
}
}
Source Code: Program to check the status of current Thread in C#
The above program generates the following output:
Status of current thread = True
To get the name of the current thread, you need to use the Name property of the Thread class. Let us see an example:
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();
}
}
}
Source Code: Program to get the name of current Thread in C#
The above program generates the following output:
Name of thread : First Thread
The Priority property of the Thread class is to be used for displaying the priority of the Current Thread:
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();
}
}
}
Source Code: Program to display the priority of current Thread in C#
The above program generates the following output:
Thread Name : First Thread
Thread Priority : Normal
Use the Sleep() method to pause the Thread for a specified period. Let us see the code now:
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();
}
}
}
Source Code: Program to pause the Thread for a specified period in C#
The above program generates the following output:
Thread Name : First Thread
Thread Priority : Normal
Child Thread Paused...
Child Thread Resumed...
Multithreading in C# significantly enhances application performance and responsiveness by executing tasks concurrently. Proper implementation and adherence to best practices, including synchronization and efficient use of TPL and async/await, are crucial. By leveraging multithreading, developers can create scalable, responsive applications. However, it's essential to manage the complexity and potential issues associated with concurrent execution. Regular testing and profiling ensure smooth and efficient performance.