SlideShare a Scribd company logo
1 of 20
Presentation By:
Live App team.
Task Parallel Library(TPL)
Agenda
• Introduction
• Life Before Async/Await
• Synchronization context
• The Lifecycle of an Async Operation
• Misconception about async/await
• Difference between CPU bound work and I/O work
• Handling Exceptions
• Report Progress/Cancellation of a task
• Unit Testing
• Combinators
• Tips and tricks
Introduction
• What is Thread?
In computer science, a thread of execution is the smallest unit of processing that can be
scheduled by an operating system.
Introduction(Cont.)
• Blocking Code VS. Non Blocking code.(Demo)
Life Before Async/Await
• example is the method on DNS that looks up the
IP address for a hostname
Asynchronous Programming Model (APM)
Life Before Async/Await(Cont.)
• Event-based Asynchronous Pattern (EAP)
Example Downloading webpage and display it.
Life Before Async/Await (Cont.)
• Why these Patterns are messy?
Synchronization context
• It represents a target for work
• It’s been in the framework for a while, but we generally haven’t had to worry about it.
• For example, in Winforms, if you get the current SynchronizationContext and do Post on it, it
does a Control.BeginInvoke. That's how Winforms gets onto the UI thread.
• And ASP.Net current synchronization context, when you do Post() on it, it schedules work to be
done in its own way.
• There are about 10 in the framework, and you can create more.
• And this is the key way that the await keyword knows how to put you back where you were.
• So when you do await, it first captures the current SyncContext before awaiting.
• When it resumes, it uses SyncContext.Post() to resume "in the same place" as it was before.
The Lifecycle of an Async Operation
Misconception about async/await
• In each async method you write, some code will be before the first occurrence of the await
keyword. Equally, some code is in the expression that gets awaited. This code always runs in
the calling thread. Nothing interesting happens before the first await.
• This is one of the most common misconceptions about async. Async never schedules your
method to run on a background thread. The only way to do that is using something like
Task.Run, which is explicitly for that purpose.
Difference between CPU bound work and I/O work
CPU bound work
* CPU-bound means things like LINQ-to-objects, or iterations, or computationally-intensive inner
loops.
*Parallel.ForEach and Task.Run are good ways to put these CPU-bound workloads on the
threadpool.
*Use of threads will never increase throughput on a machine that’s under load.
I/O bound work
*Async methods are intended to be non-blocking operations. An await expression in an async method
doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest
of the method as a continuation and returns control to the caller of the async method.(Ex. Database
requests, network access requests).
Exceptions in Async Code
Exceptions in Async Task-Returning Methods
async Task Catcher()
{
try
{
await Thrower();
}
catch (Exception)
{
// Execution will reach here
}
}
Exceptions in Async void Methods
Exceptions that leave an async void method are rethrown in the calling thread:
• If there was a SynchronizationContext when the async method was called, the exception is
Posted to it.
• If not, it is thrown on the thread pool.
Exceptions in Async void Methods (cont.)
Handle Exceptions in Async void
• In case of Console and Windows Forms application subscribe to
“AppDomain.CurrentDomain.UnhandledException” event.
• In case of Windows Store App subscribe to “Application.UnhandledException” event
AggregateException and WhenAll
List<Task> tasks = new List<Task> { Thrower1(), Thrower2()};
Task result = Task.WhenAll(tasks);
try
{
await result ;
}
catch (Exception)
{
foreach (Exception ex in result.Exception.InnerExceptions)
{}
}
Combinators
1. Task.WhenAll (params Task[] tasks)
• creates a task that will complete when all of the supplied tasks have completed. It will not block
the current execution but allows you to await the tasks for completion.
2. Task.WaitAll(params Task[] tasks)
• will wait for all of the provided Task objects to complete execution.This will block the current
execution until all tasks are done.
3. Task.WhenAny
4. Task.WaitAny :
• So if you are inside an async method, you probably want to use Task.WhenAll or WhenAny and
use await to get the results.
Tips n Tricks : Dispatcher
• On the Windows Platforms there is a rule that you cannot modify UI elements from secondary
threads. On Microsoft's XAML based platforms there is a member that exists on most UI
objects called the Dispatcher that can be used to marshal a call to the proper thread.
• Demo
• The CoreDispatcherPriority enumeration has these members.
Tips n Tricks : TaskCompletionSource
• Is a class which wraps a Task whose state
we can manually control. This is more
easily understood with an example
• It Mostly use it when only a event base
API is available
• Demo
Tips n Tricks : Configure await
• “Await task” uses the sync context
• 1. It captures the current SyncContext before awaiting.
• 2. Upon task completion, it calls SyncContext.Post() to resume “where you were before”
• You can use “await task.ConfigureAwait(false)”
• This suppresses step 2; instead if possible it resumes “on the thread that completed the task”
• Demo
Tips n Tricks : DeadLock
• Async All the Way
You should avoid mixing async and blocking code. Mixed async and blocking code can cause deadlocks,
more-complex error handling and unexpected blocking of context threads. The exception to this
guideline is the Main method for console applications, or—if you’re an advanced user—managing a
partially asynchronous codebase. Figure 5 The “Async Way” of Doing Things
• Demo
To Do This … Instead of This … Use This
Retrieve the result of a background task Task.Wait or Task.Result await
Wait for any task to complete Task.WaitAny await Task.WhenAny
Retrieve the results of multiple tasks Task.WaitAll await Task.WhenAll
Wait a period of time Thread.Sleep await Task.Delay

More Related Content

What's hot

Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET WayBishnu Rawal
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training Moutasm Tamimi
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaEdureka!
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#Bohdan Pashkovskyi
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)Abid Kohistani
 

What's hot (20)

Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
 
XML DTD and Schema
XML DTD and SchemaXML DTD and Schema
XML DTD and Schema
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programming
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
C#.NET
C#.NETC#.NET
C#.NET
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
Java keywords
Java keywordsJava keywords
Java keywords
 
C# basics
 C# basics C# basics
C# basics
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 

Similar to TPL Async Await Presentation

Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutesPaulo Morgado
 
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
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование....NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...NETFest
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Sri Kanth
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
Asynchronous Programming.pptx
Asynchronous Programming.pptxAsynchronous Programming.pptx
Asynchronous Programming.pptxAayush Chimaniya
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Need for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsKonrad Malawski
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
.Net Garbage Collector 101
.Net Garbage Collector 101.Net Garbage Collector 101
.Net Garbage Collector 101Woody Pewitt
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
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
 

Similar to TPL Async Await Presentation (20)

Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutes
 
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
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование....NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Mobile Application Development class 008
Mobile Application Development class 008Mobile Application Development class 008
Mobile Application Development class 008
 
Asynchronous Programming.pptx
Asynchronous Programming.pptxAsynchronous Programming.pptx
Asynchronous Programming.pptx
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Need for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applications
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
.Net Garbage Collector 101
.Net Garbage Collector 101.Net Garbage Collector 101
.Net Garbage Collector 101
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
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
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

TPL Async Await Presentation

  • 1. Presentation By: Live App team. Task Parallel Library(TPL)
  • 2. Agenda • Introduction • Life Before Async/Await • Synchronization context • The Lifecycle of an Async Operation • Misconception about async/await • Difference between CPU bound work and I/O work • Handling Exceptions • Report Progress/Cancellation of a task • Unit Testing • Combinators • Tips and tricks
  • 3. Introduction • What is Thread? In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system.
  • 4. Introduction(Cont.) • Blocking Code VS. Non Blocking code.(Demo)
  • 5. Life Before Async/Await • example is the method on DNS that looks up the IP address for a hostname Asynchronous Programming Model (APM)
  • 6. Life Before Async/Await(Cont.) • Event-based Asynchronous Pattern (EAP) Example Downloading webpage and display it.
  • 7. Life Before Async/Await (Cont.) • Why these Patterns are messy?
  • 8. Synchronization context • It represents a target for work • It’s been in the framework for a while, but we generally haven’t had to worry about it. • For example, in Winforms, if you get the current SynchronizationContext and do Post on it, it does a Control.BeginInvoke. That's how Winforms gets onto the UI thread. • And ASP.Net current synchronization context, when you do Post() on it, it schedules work to be done in its own way. • There are about 10 in the framework, and you can create more. • And this is the key way that the await keyword knows how to put you back where you were. • So when you do await, it first captures the current SyncContext before awaiting. • When it resumes, it uses SyncContext.Post() to resume "in the same place" as it was before.
  • 9. The Lifecycle of an Async Operation
  • 10. Misconception about async/await • In each async method you write, some code will be before the first occurrence of the await keyword. Equally, some code is in the expression that gets awaited. This code always runs in the calling thread. Nothing interesting happens before the first await. • This is one of the most common misconceptions about async. Async never schedules your method to run on a background thread. The only way to do that is using something like Task.Run, which is explicitly for that purpose.
  • 11. Difference between CPU bound work and I/O work CPU bound work * CPU-bound means things like LINQ-to-objects, or iterations, or computationally-intensive inner loops. *Parallel.ForEach and Task.Run are good ways to put these CPU-bound workloads on the threadpool. *Use of threads will never increase throughput on a machine that’s under load. I/O bound work *Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.(Ex. Database requests, network access requests).
  • 12. Exceptions in Async Code Exceptions in Async Task-Returning Methods async Task Catcher() { try { await Thrower(); } catch (Exception) { // Execution will reach here } }
  • 13. Exceptions in Async void Methods Exceptions that leave an async void method are rethrown in the calling thread: • If there was a SynchronizationContext when the async method was called, the exception is Posted to it. • If not, it is thrown on the thread pool.
  • 14. Exceptions in Async void Methods (cont.) Handle Exceptions in Async void • In case of Console and Windows Forms application subscribe to “AppDomain.CurrentDomain.UnhandledException” event. • In case of Windows Store App subscribe to “Application.UnhandledException” event
  • 15. AggregateException and WhenAll List<Task> tasks = new List<Task> { Thrower1(), Thrower2()}; Task result = Task.WhenAll(tasks); try { await result ; } catch (Exception) { foreach (Exception ex in result.Exception.InnerExceptions) {} }
  • 16. Combinators 1. Task.WhenAll (params Task[] tasks) • creates a task that will complete when all of the supplied tasks have completed. It will not block the current execution but allows you to await the tasks for completion. 2. Task.WaitAll(params Task[] tasks) • will wait for all of the provided Task objects to complete execution.This will block the current execution until all tasks are done. 3. Task.WhenAny 4. Task.WaitAny : • So if you are inside an async method, you probably want to use Task.WhenAll or WhenAny and use await to get the results.
  • 17. Tips n Tricks : Dispatcher • On the Windows Platforms there is a rule that you cannot modify UI elements from secondary threads. On Microsoft's XAML based platforms there is a member that exists on most UI objects called the Dispatcher that can be used to marshal a call to the proper thread. • Demo • The CoreDispatcherPriority enumeration has these members.
  • 18. Tips n Tricks : TaskCompletionSource • Is a class which wraps a Task whose state we can manually control. This is more easily understood with an example • It Mostly use it when only a event base API is available • Demo
  • 19. Tips n Tricks : Configure await • “Await task” uses the sync context • 1. It captures the current SyncContext before awaiting. • 2. Upon task completion, it calls SyncContext.Post() to resume “where you were before” • You can use “await task.ConfigureAwait(false)” • This suppresses step 2; instead if possible it resumes “on the thread that completed the task” • Demo
  • 20. Tips n Tricks : DeadLock • Async All the Way You should avoid mixing async and blocking code. Mixed async and blocking code can cause deadlocks, more-complex error handling and unexpected blocking of context threads. The exception to this guideline is the Main method for console applications, or—if you’re an advanced user—managing a partially asynchronous codebase. Figure 5 The “Async Way” of Doing Things • Demo To Do This … Instead of This … Use This Retrieve the result of a background task Task.Wait or Task.Result await Wait for any task to complete Task.WaitAny await Task.WhenAny Retrieve the results of multiple tasks Task.WaitAll await Task.WhenAll Wait a period of time Thread.Sleep await Task.Delay

Editor's Notes

  1. Notes -A thread is a single sequential flow of control within a program. -A thread in computer science is short for a thread of execution. Threads are a way for a program to divide (termed "split") itself into two or more simultaneously (or pseudo-simultaneously) running tasks. Threads and processes differ from one operating system to another but, in general, a thread is contained inside a process and different threads in the same process share same resources while different processes in the same multitasking operating system do not.
  2. To Do: Add table comparison.
  3. 1-The user clicks the button, so the event handler GetButton_OnClick is queued. 2. The UI thread executes the first half of GetButton_OnClick, including the call to GetFaviconAsync. 3. The UI thread continues into GetFaviconAsync and executes the first half of it, including the call to DownloadDataTaskAsync. 4. The UI thread continues into DownloadDataTaskAsync, which starts the download and returns a Task. 5. The UI thread leaves DownloadDataTaskAsync, and reaches the await in GetFaviconAsyncAsync. 6. The current SynchronizationContext is captured—it’s the UI thread. 7. GetFaviconAsync is paused by the await, and the Task from DownloadDataTask Async is told to resume it when done (with the captured SynchronizationContext). 8. The UI thread leaves GetFaviconAsync, which returned a Task, and reaches the await in GetButton_OnClick. 9.Similarly, GetButton_OnClick is paused by the await. 10. The UI thread leaves GetButton_OnClick, and is freed to work on other user actions. 11. The download finishes, so the IO completion port queues the logic in DownloadDataTaskAsync to handle that. 12. The IO completion port thread sets the Task that was returned from DownloadData TaskAsync to complete. 13. The IO completion port thread runs code inside Task to handle completion, which calls Post on the captured SynchronizationContext (the UI thread) to continue. 14. The IO completion port thread is freed to work on other IO. 15. The UI thread finds the Posted instruction and resumes GetFaviconAsync, executing the second half of it, to the end. 16. As the UI thread leaves GetFaviconAsync, it sets the Task that was returned by GetFaviconAsync to complete. 17. Because this time, the current SynchronizationContext is the same as the captured one, no Post is needed, and the UI thread proceeds synchronously. 18. The UI thread resumes GetButton_OnClick, executing the second half of it, to the end.