SlideShare una empresa de Scribd logo
1 de 19
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.

Más contenido relacionado

La actualidad más candente

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET frameworkRicha Handa
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)Prakhar Maurya
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1Mahmoud Alfarra
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Web application framework
Web application frameworkWeb application framework
Web application frameworkPankaj Chand
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Abou Bakr Ashraf
 

La actualidad más candente (20)

Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Webservices
WebservicesWebservices
Webservices
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET framework
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Web application framework
Web application frameworkWeb application framework
Web application framework
 
Client side scripting and server side scripting
Client side scripting and server side scriptingClient side scripting and server side scripting
Client side scripting and server side scripting
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Exception handling
Exception handlingException handling
Exception handling
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 

Destacado

Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Sachintha Gunasena
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVATech_MX
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Threading in c#
Threading in c#Threading in c#
Threading in c#gohsiauken
 

Destacado (7)

Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
 
Thread
ThreadThread
Thread
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Threading in c#
Threading in c#Threading in c#
Threading in c#
 

Similar a Threads And Synchronization in C#

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programmingraksharao
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 

Similar a Threads And Synchronization in C# (20)

Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
multithreading
multithreadingmultithreading
multithreading
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Multithreading
MultithreadingMultithreading
Multithreading
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 

Último

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Threads And Synchronization in C#

  • 1. Software Development Technologies Threads and Synchronization in C# Muhammad Rizwan rairizwanali@gmail.com
  • 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.