SlideShare uma empresa Scribd logo
1 de 19
Software Development Technologies
Threads and Synchronization in C#
Muhammad Nasir
m.nasir@iiu.edu.pk
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.

Mais conteúdo relacionado

Mais procurados

[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Architectural patterns part 4
Architectural patterns part 4Architectural patterns part 4
Architectural patterns part 4assinha
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNico Ludwig
 
MS SQL SERVER:Microsoft neural network and logistic regression
MS SQL SERVER:Microsoft neural network and logistic regressionMS SQL SERVER:Microsoft neural network and logistic regression
MS SQL SERVER:Microsoft neural network and logistic regressionDataminingTools Inc
 
Architectural patterns part 3
Architectural patterns part 3Architectural patterns part 3
Architectural patterns part 3assinha
 
ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner classdeepsxn
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance ConceptsEmprovise
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility PatternHüseyin Ergin
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner classsimarsimmygrewal
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked listKeval Bhogayata
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 

Mais procurados (20)

[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Architectural patterns part 4
Architectural patterns part 4Architectural patterns part 4
Architectural patterns part 4
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
 
MS SQL SERVER:Microsoft neural network and logistic regression
MS SQL SERVER:Microsoft neural network and logistic regressionMS SQL SERVER:Microsoft neural network and logistic regression
MS SQL SERVER:Microsoft neural network and logistic regression
 
Architectural patterns part 3
Architectural patterns part 3Architectural patterns part 3
Architectural patterns part 3
 
Java input
Java inputJava input
Java input
 
Scanner class
Scanner classScanner class
Scanner class
 
Friend function 6
Friend function 6Friend function 6
Friend function 6
 
ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner class
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility Pattern
 
Python session 10
Python session 10Python session 10
Python session 10
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Java applet
Java appletJava applet
Java applet
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Taking User Input in Java
Taking User Input in JavaTaking User Input in Java
Taking User Input in Java
 

Semelhante a Threads and Synchronization in c#

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
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
 
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
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
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
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in javaDucat India
 

Semelhante 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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading 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
 
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
 
multithreading
multithreadingmultithreading
multithreading
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
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
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 

Último

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 

Último (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Threads and Synchronization in c#

  • 1. Software Development Technologies Threads and Synchronization in C# Muhammad Nasir m.nasir@iiu.edu.pk
  • 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.