SlideShare a Scribd company logo
3
Most read
5
Most read
7
Most read
Software Development Technologies
Threads and Synchronization in C#
Muhammad Rizwan
rairizwanali@gmail.com
Contents






What is a Thread?
Threads in C#
Types of Threads
Threads Priority in C#
Controlling Threads in C#
What is Thread ?









In computer science, a Thread is the smallest unit of
processing that can be scheduled by an operating system.
It generally results from a fork of a computer program.
The implementation of threads and processes differs from one
operating system to another, but in most cases, a thread is
contained inside a process.
Multiple threads can exist within the same process and share
resources such as memory, while different processes do not
share these resources.
Consider the Example of a Word Processing Application i.e.,
Ms Word. Ms Word is a process and spell-checker within it is
a Thread. And the memory they share is Word document.
What is Thread ?
Threads in C#








A thread is an independent stream of instructions
in a program.
All your C# programs up to this point have one
entry point — the Main() method.
Execution starts with the first statement in the
Main() method and continues until that method
returns.
This program structure is all very well for programs
in which there is one identifiable sequence of
tasks With the Thread class, you can create and
control threads.
Threads in C#










The code here is a very simple example of creating
and starting a new thread.
The constructor of the Thread class is overloaded
to accept a delegate parameter of type ThreadStart
OR, a simple method without any return value and
input parameters.
The ThreadStart delegate defines a method with a
void return type and without arguments.
After the Thread object is created, you can start the
thread with the Start() method.
Threads in C#
using System;
using System.Threading;
namespace Wrox.ProCSharp.Threading
{
class Program
{
static void Main()
{
Thread t1 = new Thread(ThreadMain);
t1.Start();
Console.WriteLine("This is the main thread.");
}
static void ThreadMain()
{
Console.WriteLine("Running in a thread.");
}
}
}
Threads in C#


When you run the application, you get the output of
the two threads:
This is the main thread.
Running in a thread.
Types of Threads


There are two types of Threads









Foreground Threads
Background Threads

The process of the application keeps running as
long as at least one foreground thread is running.
Even if Main() method ends, the process of the
application remains active until all foreground
threads finish their work.
A thread you create with the Thread class, by
default, is a foreground thread.
Threads in C#









When you create a thread with the Thread class, you can
define whether it should be a foreground or background
thread by setting the property IsBackground.
Background threads are very useful for background tasks.
For example, when you close the Word application, it doesn’t
make sense for the spell checker to keep its process running.
The spell-checker thread can be killed when the application is
closed (Background Thread).
However, the thread organizing the Outlook message store
should remain active until it is finished, even if Outlook is
closed (Foreground Thread).
Threads Priority in C#








The operating system schedules threads based on
a priority, and the thread with the highest priority is
scheduled to run in the CPU.
With the Thread class, you can influence the priority
of the thread by setting the Priority property.
The Priority property requires a value that is defined
by the ThreadPriority enumeration.
The levels defined are Highest , AboveNormal ,
Normal , BelowNormal , and Lowest .
Controlling Threads












The thread is invoked by the Start() method of a Thread
object.
However, after invoking the Start() method, the new thread is
still not in the Running state, but in the Unstarted state.
The thread changes to the Running state as soon as the
operating system thread scheduler selects the thread to run.
You can read the current state of a thread by reading the
property Thread.ThreadState.
With the Thread.Sleep() method, a thread goes into the
WaitSleepJoin state.
And waits until it is woken up again after the time span defined
with the Sleep() method has elapsed.
Controlling Threads






To stop another thread, you can invoke the method
Thread.Abort().
When this method is called, an exception of type
ThreadAbortException is thrown in the thread that
receives the abort.
With a handler to catch this exception, the thread
can do some clean-up before it ends.
Thread Synchronization






A race condition can occur if two or more threads
access the shared data in the absence of
synchronization.
It is best to avoid synchronization issues by not
sharing data between threads. Of course, this is not
always possible.
If data sharing is necessary, you must use
synchronization techniques so that only one thread
at a time accesses and changes shared state.
Thread Synchronization
public class myClass
{
public static int count;
public void A()
{
for (int i = 0; i <100; i++)
{
count++;
}
}
}
Thread Synchronization
public class myProgram
{
Thread T1 = new Thread(A);
Thread T2 = new Thread(A);
T1.Start();
T2.Start();
Console.WriteLine(“ The count variable = {0}”,myClass.count);
}
Thread Synchronization





These two threads run as two independent threads.
If you run this program then you will discover that
the final value of count isn’t predictable because it
all depends on when the two threads get access to
count.
Every time you run this program the last value of
count variable would be different.
Thread Synchronization




C# has its own keyword for the synchronization of
multiple threads: the lock statement.
The lock statement is an easy way to hold for a lock
and release it.
public void A()
{
lock (this)
{
for (int i = 0; i <100; i++)
{
count++;
}
}
}
The End



Thanks for listening
Questions would be appreciated.

More Related Content

What's hot (20)

PPTX
C# Asynchronous delegates
Prem Kumar Badri
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PDF
Servlet and servlet life cycle
Dhruvin Nakrani
 
PPT
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
PPTX
Angularjs PPT
Amit Baghel
 
PPTX
Typescript ppt
akhilsreyas
 
PDF
JavaScript - Chapter 11 - Events
WebStackAcademy
 
PPTX
Hibernate ppt
Aneega
 
PDF
jQuery for beginners
Arulmurugan Rajaraman
 
PPTX
Windows form application - C# Training
Moutasm Tamimi
 
PPT
Java And Multithreading
Shraddha
 
PPTX
Notification android
ksheerod shri toshniwal
 
PPTX
Multithreading in java
Arafat Hossan
 
ODP
Garbage collection
Mudit Gupta
 
PPTX
Introduction to ASP.NET
Rajkumarsoy
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
Collections in-csharp
Lakshmi Mareddy
 
PPTX
Nested queries in database
Satya P. Joshi
 
PPT
Design patterns ppt
Aman Jain
 
C# Asynchronous delegates
Prem Kumar Badri
 
Servlet and servlet life cycle
Dhruvin Nakrani
 
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Angularjs PPT
Amit Baghel
 
Typescript ppt
akhilsreyas
 
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Hibernate ppt
Aneega
 
jQuery for beginners
Arulmurugan Rajaraman
 
Windows form application - C# Training
Moutasm Tamimi
 
Java And Multithreading
Shraddha
 
Notification android
ksheerod shri toshniwal
 
Multithreading in java
Arafat Hossan
 
Garbage collection
Mudit Gupta
 
Introduction to ASP.NET
Rajkumarsoy
 
Classes, objects in JAVA
Abhilash Nair
 
Collections in-csharp
Lakshmi Mareddy
 
Nested queries in database
Satya P. Joshi
 
Design patterns ppt
Aman Jain
 

Viewers also liked (8)

PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
 
PDF
Thread
Mohd Arif
 
PPT
Learning Java 3 – Threads and Synchronization
caswenson
 
PPTX
Inner Classes & Multi Threading in JAVA
Tech_MX
 
PDF
Java Thread Synchronization
Benj Del Mundo
 
PPT
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
PPTX
Threading in C#
Medhat Dawoud
 
PDF
Threading in c#
gohsiauken
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
 
Thread
Mohd Arif
 
Learning Java 3 – Threads and Synchronization
caswenson
 
Inner Classes & Multi Threading in JAVA
Tech_MX
 
Java Thread Synchronization
Benj Del Mundo
 
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Threading in C#
Medhat Dawoud
 
Threading in c#
gohsiauken
 
Ad

Similar to Threads And Synchronization in C# (20)

PDF
Intake 38 12
Mahmoud Ouf
 
PPTX
Threading
abhay singh
 
PPT
Threads-CShharp.pptsdfsdfsdgdgsdfasdfsdfasdf
SonamPandey35
 
PPT
Threads c sharp
Deivaa
 
PDF
Sync, async and multithreading
Tuan Chau
 
PPT
Introto netthreads-090906214344-phpapp01
Aravindharamanan S
 
PDF
Threading in c_sharp
Tiago
 
PPT
Intro To .Net Threads
rchakra
 
PPT
Threads c sharp
Karthick Suresh
 
PDF
.Net Threading
Erik Ralston
 
PPTX
Multithreading and concurrency.pptx
ShymmaaQadoom1
 
PDF
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
NETFest
 
PDF
Threading
j25ankur
 
PDF
.NET Multithreading and File I/O
Jussi Pohjolainen
 
PPTX
concurrency_c#_public
Paul Churchward
 
PDF
Concurrency and parallel in .net
Mohammad Hossein Karami
 
PPT
Csphtp1 14
HUST
 
PPS
11 iec t1_s1_oo_ps_session_16
Niit Care
 
PPTX
C# Async/Await Explained
Jeremy Likness
 
Intake 38 12
Mahmoud Ouf
 
Threading
abhay singh
 
Threads-CShharp.pptsdfsdfsdgdgsdfasdfsdfasdf
SonamPandey35
 
Threads c sharp
Deivaa
 
Sync, async and multithreading
Tuan Chau
 
Introto netthreads-090906214344-phpapp01
Aravindharamanan S
 
Threading in c_sharp
Tiago
 
Intro To .Net Threads
rchakra
 
Threads c sharp
Karthick Suresh
 
.Net Threading
Erik Ralston
 
Multithreading and concurrency.pptx
ShymmaaQadoom1
 
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
NETFest
 
Threading
j25ankur
 
.NET Multithreading and File I/O
Jussi Pohjolainen
 
concurrency_c#_public
Paul Churchward
 
Concurrency and parallel in .net
Mohammad Hossein Karami
 
Csphtp1 14
HUST
 
11 iec t1_s1_oo_ps_session_16
Niit Care
 
C# Async/Await Explained
Jeremy Likness
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 

Threads And Synchronization in C#

  • 1. Software Development Technologies Threads and Synchronization in C# Muhammad Rizwan [email protected]
  • 2. Contents      What is a Thread? Threads in C# Types of Threads Threads Priority in C# Controlling Threads in C#
  • 3. What is Thread ?      In computer science, a Thread is the smallest unit of processing that can be scheduled by an operating system. It generally results from a fork of a computer program. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources. Consider the Example of a Word Processing Application i.e., Ms Word. Ms Word is a process and spell-checker within it is a Thread. And the memory they share is Word document.
  • 5. Threads in C#     A thread is an independent stream of instructions in a program. All your C# programs up to this point have one entry point — the Main() method. Execution starts with the first statement in the Main() method and continues until that method returns. This program structure is all very well for programs in which there is one identifiable sequence of tasks With the Thread class, you can create and control threads.
  • 6. Threads in C#      The code here is a very simple example of creating and starting a new thread. The constructor of the Thread class is overloaded to accept a delegate parameter of type ThreadStart OR, a simple method without any return value and input parameters. The ThreadStart delegate defines a method with a void return type and without arguments. After the Thread object is created, you can start the thread with the Start() method.
  • 7. Threads in C# using System; using System.Threading; namespace Wrox.ProCSharp.Threading { class Program { static void Main() { Thread t1 = new Thread(ThreadMain); t1.Start(); Console.WriteLine("This is the main thread."); } static void ThreadMain() { Console.WriteLine("Running in a thread."); } } }
  • 8. Threads in C#  When you run the application, you get the output of the two threads: This is the main thread. Running in a thread.
  • 9. Types of Threads  There are two types of Threads      Foreground Threads Background Threads The process of the application keeps running as long as at least one foreground thread is running. Even if Main() method ends, the process of the application remains active until all foreground threads finish their work. A thread you create with the Thread class, by default, is a foreground thread.
  • 10. Threads in C#      When you create a thread with the Thread class, you can define whether it should be a foreground or background thread by setting the property IsBackground. Background threads are very useful for background tasks. For example, when you close the Word application, it doesn’t make sense for the spell checker to keep its process running. The spell-checker thread can be killed when the application is closed (Background Thread). However, the thread organizing the Outlook message store should remain active until it is finished, even if Outlook is closed (Foreground Thread).
  • 11. Threads Priority in C#     The operating system schedules threads based on a priority, and the thread with the highest priority is scheduled to run in the CPU. With the Thread class, you can influence the priority of the thread by setting the Priority property. The Priority property requires a value that is defined by the ThreadPriority enumeration. The levels defined are Highest , AboveNormal , Normal , BelowNormal , and Lowest .
  • 12. Controlling Threads       The thread is invoked by the Start() method of a Thread object. However, after invoking the Start() method, the new thread is still not in the Running state, but in the Unstarted state. The thread changes to the Running state as soon as the operating system thread scheduler selects the thread to run. You can read the current state of a thread by reading the property Thread.ThreadState. With the Thread.Sleep() method, a thread goes into the WaitSleepJoin state. And waits until it is woken up again after the time span defined with the Sleep() method has elapsed.
  • 13. Controlling Threads    To stop another thread, you can invoke the method Thread.Abort(). When this method is called, an exception of type ThreadAbortException is thrown in the thread that receives the abort. With a handler to catch this exception, the thread can do some clean-up before it ends.
  • 14. Thread Synchronization    A race condition can occur if two or more threads access the shared data in the absence of synchronization. It is best to avoid synchronization issues by not sharing data between threads. Of course, this is not always possible. If data sharing is necessary, you must use synchronization techniques so that only one thread at a time accesses and changes shared state.
  • 15. Thread Synchronization public class myClass { public static int count; public void A() { for (int i = 0; i <100; i++) { count++; } } }
  • 16. Thread Synchronization public class myProgram { Thread T1 = new Thread(A); Thread T2 = new Thread(A); T1.Start(); T2.Start(); Console.WriteLine(“ The count variable = {0}”,myClass.count); }
  • 17. Thread Synchronization    These two threads run as two independent threads. If you run this program then you will discover that the final value of count isn’t predictable because it all depends on when the two threads get access to count. Every time you run this program the last value of count variable would be different.
  • 18. Thread Synchronization   C# has its own keyword for the synchronization of multiple threads: the lock statement. The lock statement is an easy way to hold for a lock and release it. public void A() { lock (this) { for (int i = 0; i <100; i++) { count++; } } }
  • 19. The End   Thanks for listening Questions would be appreciated.