SlideShare a Scribd company logo
1 of 41
Concurrency in C#
A Classroom Presentation for Cloud Computing at Tarbiat Modarres
University
By:
Sajjad Gholamipour
Reza Hamidpour
Related professor:
Dr. Sadegh Dorri
University of Tarbiat modares
Faculty of Electrical and Computer
Department of Computer Engineering
1
Concurrency: An Overview
 Concurrency is a key aspect of beautiful software
 For decades, concurrency was possible but difficult
 Concurrent software was difficult to write, difficult to debug, and difficult
to maintain
 As a result, many developers chose the easier path and avoided
concurrency
1
Concurrency: An Overview
 However, with the libraries and language features available for modern
.NET programs, concurrency is much easier
 When Visual Studio 2012 was released, Microsoft significantly lowered
the bar for concurrency
 Previously, concurrent programming was the domain of experts; these
days, every developer can (and should) embrace concurrency
2
Terminology
 Concurrency
Doing more than one thing at a time
 Multithreading
A form of concurrency that uses multiple threads of execution
 Parallel Processing
Doing lots of work by dividing it up among multiple threads that run
concurrently
 Asynchronous Programming
A form of concurrency that uses futures or callbacks to avoid
unnecessary threads
 Reactive Programming
A declarative style of programming where the application reacts to
events
3
Concurrency: Benefits
 End-user applications use concurrency to respond to user
input while writing to a database
 Server applications use concurrency to respond to a second
request while finishing the first request
 You need concurrency any time you need an application to do one
thing while it’s working on something else
 Almost every software application in the world can benefit from
concurrency
4
Multithreading
 Multithreading literally refers to using multiple threads
 Multithreading is one form of concurrency, but certainly not the only one
 A thread is an independent executor
 Each process has multiple threads in it, and each of those threads can be
doing different things simultaneously
 Each thread has its own independent stack but shares the same memory
with all the other threads in a process
5
Multithreading
 In some applications, there is one thread that is special
 User interface applications have a single UI thread; Console applications
have a single main thread
 In fact, direct use of the low-level threading types has almost no purpose
in a modern application
 Higher-level abstractions are more powerful and more efficient than old-
school multithreading
6
Multithreading
 But don’t get the idea that multithreading is dead
 Multithreading lives on in the thread pool, a useful place to queue work
that automatically adjusts itself according to demand
 Every .NET application has a thread pool
 The thread pool maintains a number of worker threads that are waiting to
execute whatever work you have for them to do
7
Multithreading
 The thread pool is responsible for determining how many threads are in
the thread pool at any time
 There are dozens of configuration settings you can play with to modify
this behavior, but I recommend that you leave it alone; the thread pool has
been carefully tuned to cover the vast majority of real-world scenarios
 There is almost no need to ever create a new thread yourself
8
Parallel Programming
 Parallel programming should be used any time you have a fair amount of
computation work that can be split up into independent chunks of work
 Parallel programming increases the CPU usage temporarily to improve
throughput; this is desirable on client systems where CPUs are often idle
but is usually not appropriate for server systems
9
Parallel Programming
 Parallel processing (or parallel programming) uses multithreading to
maximize the use of multiple processors
 Modern CPUs have multiple cores, and if there’s a lot of work to do, then
it makes no sense to just make one core do all the work while the others
sit idle
 Parallel processing will split up the work among multiple threads, which
can each run independently on a different core
 Parallel processing is one type of multithreading, and multithreading is
one type of concurrency
10
Asynchronous Programming
 There’s another type of concurrency that is important in modern
applications but is not (currently) familiar to many
developers: asynchronous programming
 A future, a type that represents some operation that will complete in the
future
 future types in .NET are Task and Task<TResult>. Older asynchronous
APIs use callbacks or events instead of futures
11
Asynchronous Programming
 Asynchronous programming is centered around the idea of an
asynchronous operation: some operation that is started that will complete
some time later
 While the operation is in progress, it does not block the original thread;
the thread that starts the operation is free to do other work
 When the operation completes, it notifies its future or invokes its
completion callback event to let the application know the operation is
finished
12
Asynchronous Programming
 Asynchronous programming is a powerful form of concurrency, but until
recently, it required extremely complex code
 The async and await support in VS2012 make asynchronous
programming almost as easy as synchronous (nonconcurrent)
programming
 Modern asynchronous .NET applications use two keywords:
 async
 await
13
Asynchronous Programming
 The async keyword is added to a method declaration, and its
primary purpose is to enable the await keyword within that
method
 An async method should return Task<T> if it returns a value, or
Task if it does not return a value
 These task types represent futures; they notify the calling code
when the async method completes
14
Asynchronous Programming15
Reactive Programming
 Another form of concurrency is reactive programming
 Asynchronous programming implies that the application will start an
operation that will complete once at a later time
 Reactive programming is closely related to asynchronous
programming, but is built on asynchronous events instead of
asynchronous operations
16
Reactive Programming
 Asynchronous events may not have an actual “start,” may happen at any
time, and may be raised multiple times
 One example is user input
 If you consider an application to be a massive state machine, the
application’s behavior can be described as reacting to a series of events by
updating its state at each event
17
Reactive Programming
 This is not as abstract or theoretical as it sounds; modern frameworks
make this approach quite useful in real-world applications
 Reactive programming is not necessarily concurrent, but it is closely
related to concurrency
18
Reactive Programming
 Reactive programming has a higher learning curve than other forms of
concurrency, and the code can be harder to maintain unless you keep up
with your reactive skills
 If you’re willing to learn it, though, reactive programming is extremely
powerful
 Reactive programming allows you to treat a stream of events like a stream
of data
19
NOTATION
 Usually, a mixture of techniques are used in a concurrent program
 Most applications at least use multithreading (via the thread pool) and
asynchronous programming
 Feel free to mix and match all the various forms of concurrency, using the
appropriate tool for each part of the application
20
Multithreading: Implementation
principles-thread and types
 To perform any multiple task simultaneously means Threading
 For example executing Microsoft PPTX and Excel simultaneously in a
desktop, laptop or any device is known as Threading
 Work or a code task is always been executed in a two ways i.e.
Synchronous or Asynchronous way
 Synchronous way means where work multiple jobs are executed one after
the other
21
Multithreading: Implementation
principles-thread and types
 Synchronous way means where work multiple jobs are executed one after
the other
22
Multithreading: Implementation
principles-thread and types
 Asynchronous means multiple work has been executed simultaneously
like doing multitask at a same time
23
Multithreading: Implementation
principles-thread and types
 C# widely supports threading in Console Application, Windows Form,
WPF so when we create a new thread in a console app it means we are
making it multithread environment
24
Multithreading: Implementation
principles-thread and types
For creating threading application there some important methods which used
regularly for implementing threading
 Thread Join
 Thread Sleep
 Thread Abort
25
Multithreading: Implementation
principles-thread and types
Thread Join
 Thread.Join() make thread to finish its work or makes other thread to halt until
it finishes work
 Join method when attached to any thread, it makes that thread to execute first
and halts other threads
26
Multithreading: Implementation
principles-thread and types
Thread Sleep
 Thread.Sleep() a method used to suspend current thread for a specific interval
of time
 Time can be specified in milliseconds or Timespan
 While in a Sleep mode a method does not consumes any CPU resources so
indirectly it save memory for other thread processes
27
Multithreading: Implementation
principles-thread and types
Thread Abort
 As name implies "Abort" so same way Thread
 Abort helps to end or abort any thread to process it further
28
Multithreading: Implementation
principles-thread and types
Types of thread in C#:
 Foreground Thread
 Background Thread
29
Multithreading: Implementation
principles-thread and types
Foreground Thread
 Foreground threads are those threads which keeps running until it finishes
his work even if the Main method thread quits its process
 Lifespan of foreground threads does not depends on main thread
30
Multithreading: Implementation
principles-thread and types
Background Thread
 Background thread is just opposite of foreground thread here background
thread quits its job when main thread quits
 Here lifespan of background threads depends on main thread
31
Multithreading: Implementation
principles-Thread Safety
 To control abnormal behaviour of an object in a multi-threaded
environment is called as Thread Safety
 In order to make a thread as thread safe there are some thread
synchronization techniques like:
 Monitor/Lock
 Mutex
 Semaphore
 SemaphoreSlim
32
Multithreading: Implementation
principles-Thread Safety
33
Multithreading: Implementation
principles-Thread Pooling
 let's understand life cycle of thread
 When a .NET framework receives request of a method call then it creates
new thread object which gets allocated on memory and then it executes
task
 Once the task gets complete then garbage collector removes that thread
object for free-up memory allocation
 So this life cycle of a thread
34
Multithreading: Implementation
principles-Thread Pooling
35
Multithreading: Implementation
principles-Thread Pooling
 Thread Pooling in Csharp
36
Multithreading: Implementation
principles-Thread Pooling
37
Practical section
 Sequential vs threading
 Forground and Background
 Thread safety
 Thread pooling
 Asynchronous programming
 Async-await
 Begin-end invoke
38
References
 Concurrency in C# Cookbook by Stephen Cleary
 https://www.oreilly.com/library/view/concurrency-in-
c/9781491906675/ch01.html
 Learn C# tutorial
 http://www.learncsharptutorial.com/threading-and-types-of-
threading-stepbystep.php
 http://www.learncsharptutorial.com/thready-safely-csharp.php
 http://www.learncsharptutorial.com/threadpooling-csharp-
example.php
39
Thank you for attention
41

More Related Content

What's hot

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Lecture 4 principles of parallel algorithm design updated
Lecture 4   principles of parallel algorithm design updatedLecture 4   principles of parallel algorithm design updated
Lecture 4 principles of parallel algorithm design updatedVajira Thambawita
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guidelineDhananjaysinh Jhala
 
Levels of Virtualization.docx
Levels of Virtualization.docxLevels of Virtualization.docx
Levels of Virtualization.docxkumari36
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagramSadhana28
 
Multithreading
MultithreadingMultithreading
MultithreadingA B Shinde
 
History of virtualization
History of virtualizationHistory of virtualization
History of virtualizationmaria azam
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Distributed computing
Distributed computingDistributed computing
Distributed computingshivli0769
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton PatternMudasir Qazi
 

What's hot (20)

Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Shell programming
Shell programmingShell programming
Shell programming
 
Lecture 4 principles of parallel algorithm design updated
Lecture 4   principles of parallel algorithm design updatedLecture 4   principles of parallel algorithm design updated
Lecture 4 principles of parallel algorithm design updated
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Levels of Virtualization.docx
Levels of Virtualization.docxLevels of Virtualization.docx
Levels of Virtualization.docx
 
VLIW Processors
VLIW ProcessorsVLIW Processors
VLIW Processors
 
Cluster Computing
Cluster ComputingCluster Computing
Cluster Computing
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Distributed Computing ppt
Distributed Computing pptDistributed Computing ppt
Distributed Computing ppt
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
 
Underlying principles of parallel and distributed computing
Underlying principles of parallel and distributed computingUnderlying principles of parallel and distributed computing
Underlying principles of parallel and distributed computing
 
Multithreading
MultithreadingMultithreading
Multithreading
 
History of virtualization
History of virtualizationHistory of virtualization
History of virtualization
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Core java
Core java Core java
Core java
 
OOP java
OOP javaOOP java
OOP java
 
Distributed computing
Distributed computingDistributed computing
Distributed computing
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
 

Similar to Concurrency in c#

Towards high performance computing(hpc) through parallel programming paradigm...
Towards high performance computing(hpc) through parallel programming paradigm...Towards high performance computing(hpc) through parallel programming paradigm...
Towards high performance computing(hpc) through parallel programming paradigm...ijpla
 
parallel programming models
 parallel programming models parallel programming models
parallel programming modelsSwetha S
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingOlivier NAVARRE
 
Tutorial on Parallel Computing and Message Passing Model - C1
Tutorial on Parallel Computing and Message Passing Model - C1Tutorial on Parallel Computing and Message Passing Model - C1
Tutorial on Parallel Computing and Message Passing Model - C1Marcirio Chaves
 
Threading Programming Guide
Threading Programming GuideThreading Programming Guide
Threading Programming GuideDEVTYPE
 
198970820 p-oooooooooo
198970820 p-oooooooooo198970820 p-oooooooooo
198970820 p-oooooooooohomeworkping4
 
5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptx5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptxMohamedBilal73
 
LOCK-FREE PARALLEL ACCESS COLLECTIONS
LOCK-FREE PARALLEL ACCESS COLLECTIONSLOCK-FREE PARALLEL ACCESS COLLECTIONS
LOCK-FREE PARALLEL ACCESS COLLECTIONSijdpsjournal
 
Lock free parallel access collections
Lock free parallel access collectionsLock free parallel access collections
Lock free parallel access collectionsijdpsjournal
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingPraveen Prajapati
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingJuti Noppornpitak
 
Parallelization using open mp
Parallelization using open mpParallelization using open mp
Parallelization using open mpranjit banshpal
 
C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programmingUmeshwaran V
 
Multicore_Architecture Book.pdf
Multicore_Architecture Book.pdfMulticore_Architecture Book.pdf
Multicore_Architecture Book.pdfSwatantraPrakash5
 

Similar to Concurrency in c# (20)

Towards high performance computing(hpc) through parallel programming paradigm...
Towards high performance computing(hpc) through parallel programming paradigm...Towards high performance computing(hpc) through parallel programming paradigm...
Towards high performance computing(hpc) through parallel programming paradigm...
 
parallel programming models
 parallel programming models parallel programming models
parallel programming models
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel Programming
 
Tutorial on Parallel Computing and Message Passing Model - C1
Tutorial on Parallel Computing and Message Passing Model - C1Tutorial on Parallel Computing and Message Passing Model - C1
Tutorial on Parallel Computing and Message Passing Model - C1
 
Threading Programming Guide
Threading Programming GuideThreading Programming Guide
Threading Programming Guide
 
198970820 p-oooooooooo
198970820 p-oooooooooo198970820 p-oooooooooo
198970820 p-oooooooooo
 
Aq4301224227
Aq4301224227Aq4301224227
Aq4301224227
 
5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptx5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptx
 
Threads
ThreadsThreads
Threads
 
LOCK-FREE PARALLEL ACCESS COLLECTIONS
LOCK-FREE PARALLEL ACCESS COLLECTIONSLOCK-FREE PARALLEL ACCESS COLLECTIONS
LOCK-FREE PARALLEL ACCESS COLLECTIONS
 
Lock free parallel access collections
Lock free parallel access collectionsLock free parallel access collections
Lock free parallel access collections
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
 
J threads-pdf
J threads-pdfJ threads-pdf
J threads-pdf
 
Linux Memory Management
Linux Memory ManagementLinux Memory Management
Linux Memory Management
 
Java multi thread programming on cmp system
Java multi thread programming on cmp systemJava multi thread programming on cmp system
Java multi thread programming on cmp system
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Parallelization using open mp
Parallelization using open mpParallelization using open mp
Parallelization using open mp
 
Multithreading
MultithreadingMultithreading
Multithreading
 
C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
 
Multicore_Architecture Book.pdf
Multicore_Architecture Book.pdfMulticore_Architecture Book.pdf
Multicore_Architecture Book.pdf
 

Recently uploaded

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 

Recently uploaded (20)

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 

Concurrency in c#

  • 1. Concurrency in C# A Classroom Presentation for Cloud Computing at Tarbiat Modarres University By: Sajjad Gholamipour Reza Hamidpour Related professor: Dr. Sadegh Dorri University of Tarbiat modares Faculty of Electrical and Computer Department of Computer Engineering 1
  • 2. Concurrency: An Overview  Concurrency is a key aspect of beautiful software  For decades, concurrency was possible but difficult  Concurrent software was difficult to write, difficult to debug, and difficult to maintain  As a result, many developers chose the easier path and avoided concurrency 1
  • 3. Concurrency: An Overview  However, with the libraries and language features available for modern .NET programs, concurrency is much easier  When Visual Studio 2012 was released, Microsoft significantly lowered the bar for concurrency  Previously, concurrent programming was the domain of experts; these days, every developer can (and should) embrace concurrency 2
  • 4. Terminology  Concurrency Doing more than one thing at a time  Multithreading A form of concurrency that uses multiple threads of execution  Parallel Processing Doing lots of work by dividing it up among multiple threads that run concurrently  Asynchronous Programming A form of concurrency that uses futures or callbacks to avoid unnecessary threads  Reactive Programming A declarative style of programming where the application reacts to events 3
  • 5. Concurrency: Benefits  End-user applications use concurrency to respond to user input while writing to a database  Server applications use concurrency to respond to a second request while finishing the first request  You need concurrency any time you need an application to do one thing while it’s working on something else  Almost every software application in the world can benefit from concurrency 4
  • 6. Multithreading  Multithreading literally refers to using multiple threads  Multithreading is one form of concurrency, but certainly not the only one  A thread is an independent executor  Each process has multiple threads in it, and each of those threads can be doing different things simultaneously  Each thread has its own independent stack but shares the same memory with all the other threads in a process 5
  • 7. Multithreading  In some applications, there is one thread that is special  User interface applications have a single UI thread; Console applications have a single main thread  In fact, direct use of the low-level threading types has almost no purpose in a modern application  Higher-level abstractions are more powerful and more efficient than old- school multithreading 6
  • 8. Multithreading  But don’t get the idea that multithreading is dead  Multithreading lives on in the thread pool, a useful place to queue work that automatically adjusts itself according to demand  Every .NET application has a thread pool  The thread pool maintains a number of worker threads that are waiting to execute whatever work you have for them to do 7
  • 9. Multithreading  The thread pool is responsible for determining how many threads are in the thread pool at any time  There are dozens of configuration settings you can play with to modify this behavior, but I recommend that you leave it alone; the thread pool has been carefully tuned to cover the vast majority of real-world scenarios  There is almost no need to ever create a new thread yourself 8
  • 10. Parallel Programming  Parallel programming should be used any time you have a fair amount of computation work that can be split up into independent chunks of work  Parallel programming increases the CPU usage temporarily to improve throughput; this is desirable on client systems where CPUs are often idle but is usually not appropriate for server systems 9
  • 11. Parallel Programming  Parallel processing (or parallel programming) uses multithreading to maximize the use of multiple processors  Modern CPUs have multiple cores, and if there’s a lot of work to do, then it makes no sense to just make one core do all the work while the others sit idle  Parallel processing will split up the work among multiple threads, which can each run independently on a different core  Parallel processing is one type of multithreading, and multithreading is one type of concurrency 10
  • 12. Asynchronous Programming  There’s another type of concurrency that is important in modern applications but is not (currently) familiar to many developers: asynchronous programming  A future, a type that represents some operation that will complete in the future  future types in .NET are Task and Task<TResult>. Older asynchronous APIs use callbacks or events instead of futures 11
  • 13. Asynchronous Programming  Asynchronous programming is centered around the idea of an asynchronous operation: some operation that is started that will complete some time later  While the operation is in progress, it does not block the original thread; the thread that starts the operation is free to do other work  When the operation completes, it notifies its future or invokes its completion callback event to let the application know the operation is finished 12
  • 14. Asynchronous Programming  Asynchronous programming is a powerful form of concurrency, but until recently, it required extremely complex code  The async and await support in VS2012 make asynchronous programming almost as easy as synchronous (nonconcurrent) programming  Modern asynchronous .NET applications use two keywords:  async  await 13
  • 15. Asynchronous Programming  The async keyword is added to a method declaration, and its primary purpose is to enable the await keyword within that method  An async method should return Task<T> if it returns a value, or Task if it does not return a value  These task types represent futures; they notify the calling code when the async method completes 14
  • 17. Reactive Programming  Another form of concurrency is reactive programming  Asynchronous programming implies that the application will start an operation that will complete once at a later time  Reactive programming is closely related to asynchronous programming, but is built on asynchronous events instead of asynchronous operations 16
  • 18. Reactive Programming  Asynchronous events may not have an actual “start,” may happen at any time, and may be raised multiple times  One example is user input  If you consider an application to be a massive state machine, the application’s behavior can be described as reacting to a series of events by updating its state at each event 17
  • 19. Reactive Programming  This is not as abstract or theoretical as it sounds; modern frameworks make this approach quite useful in real-world applications  Reactive programming is not necessarily concurrent, but it is closely related to concurrency 18
  • 20. Reactive Programming  Reactive programming has a higher learning curve than other forms of concurrency, and the code can be harder to maintain unless you keep up with your reactive skills  If you’re willing to learn it, though, reactive programming is extremely powerful  Reactive programming allows you to treat a stream of events like a stream of data 19
  • 21. NOTATION  Usually, a mixture of techniques are used in a concurrent program  Most applications at least use multithreading (via the thread pool) and asynchronous programming  Feel free to mix and match all the various forms of concurrency, using the appropriate tool for each part of the application 20
  • 22. Multithreading: Implementation principles-thread and types  To perform any multiple task simultaneously means Threading  For example executing Microsoft PPTX and Excel simultaneously in a desktop, laptop or any device is known as Threading  Work or a code task is always been executed in a two ways i.e. Synchronous or Asynchronous way  Synchronous way means where work multiple jobs are executed one after the other 21
  • 23. Multithreading: Implementation principles-thread and types  Synchronous way means where work multiple jobs are executed one after the other 22
  • 24. Multithreading: Implementation principles-thread and types  Asynchronous means multiple work has been executed simultaneously like doing multitask at a same time 23
  • 25. Multithreading: Implementation principles-thread and types  C# widely supports threading in Console Application, Windows Form, WPF so when we create a new thread in a console app it means we are making it multithread environment 24
  • 26. Multithreading: Implementation principles-thread and types For creating threading application there some important methods which used regularly for implementing threading  Thread Join  Thread Sleep  Thread Abort 25
  • 27. Multithreading: Implementation principles-thread and types Thread Join  Thread.Join() make thread to finish its work or makes other thread to halt until it finishes work  Join method when attached to any thread, it makes that thread to execute first and halts other threads 26
  • 28. Multithreading: Implementation principles-thread and types Thread Sleep  Thread.Sleep() a method used to suspend current thread for a specific interval of time  Time can be specified in milliseconds or Timespan  While in a Sleep mode a method does not consumes any CPU resources so indirectly it save memory for other thread processes 27
  • 29. Multithreading: Implementation principles-thread and types Thread Abort  As name implies "Abort" so same way Thread  Abort helps to end or abort any thread to process it further 28
  • 30. Multithreading: Implementation principles-thread and types Types of thread in C#:  Foreground Thread  Background Thread 29
  • 31. Multithreading: Implementation principles-thread and types Foreground Thread  Foreground threads are those threads which keeps running until it finishes his work even if the Main method thread quits its process  Lifespan of foreground threads does not depends on main thread 30
  • 32. Multithreading: Implementation principles-thread and types Background Thread  Background thread is just opposite of foreground thread here background thread quits its job when main thread quits  Here lifespan of background threads depends on main thread 31
  • 33. Multithreading: Implementation principles-Thread Safety  To control abnormal behaviour of an object in a multi-threaded environment is called as Thread Safety  In order to make a thread as thread safe there are some thread synchronization techniques like:  Monitor/Lock  Mutex  Semaphore  SemaphoreSlim 32
  • 35. Multithreading: Implementation principles-Thread Pooling  let's understand life cycle of thread  When a .NET framework receives request of a method call then it creates new thread object which gets allocated on memory and then it executes task  Once the task gets complete then garbage collector removes that thread object for free-up memory allocation  So this life cycle of a thread 34
  • 39. Practical section  Sequential vs threading  Forground and Background  Thread safety  Thread pooling  Asynchronous programming  Async-await  Begin-end invoke 38
  • 40. References  Concurrency in C# Cookbook by Stephen Cleary  https://www.oreilly.com/library/view/concurrency-in- c/9781491906675/ch01.html  Learn C# tutorial  http://www.learncsharptutorial.com/threading-and-types-of- threading-stepbystep.php  http://www.learncsharptutorial.com/thready-safely-csharp.php  http://www.learncsharptutorial.com/threadpooling-csharp- example.php 39
  • 41. Thank you for attention 41