SlideShare une entreprise Scribd logo
1  sur  34
Your Cloud.
Your Business.
C# Async and Await Explained
Jeremy Likness
Principal Architect
@JeremyLikness
Our Mission, Vision, and Values
Our Solutions
TODAY’S AGENDA
1. Why? Why do we need new keywords?
2. What? What exactly do async and await do?
3. How? How and when should async and await be used?
4. Q&A You have questions, I have answers
WHY?
WHY? Fundamentals
• Once upon a time, an OS was created to run apps
• These apps would run in a process
• Processes would be segregated into app domains
• App domains would run threads
Process
App Domain 1
•Thread 1
•Thread 2
App Domain 2
•Thread 3
•Thread 4
• Process is the running program,
i.e. the .NET CLR host
• App domains provide isolation
from each other and can be
uniquely configured, loaded,
unloaded, and secured
• Threads enable management of
code execution
WHY? What’s in every thread
…
Thread kernel object
(context) ~1KB
Thread environment
block (local storage
data, graphics,
exception handling)
~4KB – 8KB
User mode stack ~1MB
Kernel mode stack
~20KB
WHY? The life of one thread…
Initialize
memory
Thread
attach
notifications
sent to every
DLL in the
process
Execute code
Context
Switch
Execute Code
Thread
detach
notifications
Deallocate
memory
WHY? Thread scheduling (1 core)
WHY? And to think …
DEMO: Threads
WHY? A Dip in the Thread Pool
• We agree threads have overhead
• To address this, the CLR introduces the thread pool
• Starts out empty
• As tasks are dispatched, threads are created
• When thread is done, it is returned to the pool and recycled
• Trade-offs exist:
• Less overhead (memory pressure)
• Less time to allocate/spin up a thread
• However, fewer threads are scheduled concurrently
DEMO: Thread Pool
WHY? Tasks
• Make it easier to deal with threads and the thread pool
• Easy to wait
• Automatic ability to cancel
• Simple access to result
• Chainable tasks (one starts when the other finishes)
• Child tasks
• Parallel functions
DEMO: Tasks
WHY? I/O Operations
I/O
Request
Packet
Make I/O
Request
Device
Driver
Queue
Driver
Does I/O
Thread
Goes to
Sleep
Thread
Wakes Up
WHY? Synchronous: Two Threads
Handle Request Blocked I/O Complete
Handle Request Blocked I/O Complete
WHY? Asynchronous: One Thread
Handle Request CompleteHandle Request Complete
Asynchronous Asynchronous
DEMO: Asynchronous
WHAT?
What? async
• Expecting to use await
• Does not create new thread, always uses same thread as
caller
• After await may or may not use same thread (thread pool is
involved, so threads are reusable)
• If a SynchronizationContet exists, it will return to that
thread
• You can also modify this behavior using ConfigureAwait
• Basically … think “yield” for threads!
What? Yield: a refresher
DEMO: Async
Best Practices
• Never async void (use Task instead)
• Exceptions can’t be caught so they are thrown in the
context (if you have one!)
• Made specifically for event handlers
• If you must use for event handler, try to isolate the
majority of code in another await that does return a
Task
• Never mix async and blocking code together
• Task.Wait, Task.Result are generally bad ideas
• Exception is a console application
• From the necessary static main, promote to an async
static main with a wait
• Task.Wait should become Task.When
HOW?
How?
• More impactful for I/O bound than compute-bound
• Remember the Fibonacci examples?
• Check this out …
DEMO: Async ThreadPool
How?
• “I usually don’t work with multi-threading”
• If you are working on the web, you are in a multi-threaded
environment
• If you are I/O bound, you should take advantage
• Entity Framework now supports asynchronous methods!
• The transformation is simple …
How? Asynchronous Controllers
How? Real World Results
Source: http://blog.stevensanderson.com/2010/01/
How? Windows 8.x / 10 or whatever
• Windows Runtime (WinRT)
• IAsyncInfo
• IAsyncAction
• IAsyncOperation<TResult>
• IAsyncActionWithProgress<TProgress>
• IAsyncOperationWithProgress<TResult, TProgress>
• ThreadPool.RunAsync
• IAsyncInfo.AsTask()
Recap
• You are always working with multi-threaded, don’t sell
yourself short!
• Compute-bound does not benefit as much from
asynchronous as you might think, except to free the main
context (typically your UI thread)
• I/O has tremendous benefits
• Async does not spin up a new thread. Instead, it establishes
a state machine and makes the thread reusable and re-
entrant
• Await is not like Wait() because it doesn’t block and it allows
you to recycle threads
• If you have async I/O then USE IT! Async Task<> is your
friend.
Deck and Source
https://github.com/JeremyLikness/AsyncAwaitExplained
Questions?
http://ivision.com/author/jlikness/
@JeremyLikness
http://linkedin.com/in/jeremylikness
http://plus.google.com/+jeremylikness
http://stackoverflow.com/users/228918/jeremy-likness
https://github.com/JeremyLikness
http://csharperimage.jeremylikness.com/

Contenu connexe

Tendances

Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With JestBen McCormick
 
Intro to Service Worker API and its use cases
Intro to Service Worker API and its use casesIntro to Service Worker API and its use cases
Intro to Service Worker API and its use casessatejsahu
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSébastien Levert
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
Fast Track introduction to ASP.NET MVC
Fast Track introduction to ASP.NET MVCFast Track introduction to ASP.NET MVC
Fast Track introduction to ASP.NET MVCAnkit Kashyap
 
Single Page Applications in SharePoint with Angular
Single Page Applications in SharePoint with AngularSingle Page Applications in SharePoint with Angular
Single Page Applications in SharePoint with AngularSparkhound Inc.
 
An afternoon with angular 2
An afternoon with angular 2An afternoon with angular 2
An afternoon with angular 2Mike Melusky
 
SPA, Scalable Application & AngularJS
SPA, Scalable Application & AngularJSSPA, Scalable Application & AngularJS
SPA, Scalable Application & AngularJSMitch Chen
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Dawid Myslak
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance TestingAlan Hecht
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 

Tendances (20)

Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 
Intro to Service Worker API and its use cases
Intro to Service Worker API and its use casesIntro to Service Worker API and its use cases
Intro to Service Worker API and its use cases
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Angular js
Angular jsAngular js
Angular js
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure Functions
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Fast Track introduction to ASP.NET MVC
Fast Track introduction to ASP.NET MVCFast Track introduction to ASP.NET MVC
Fast Track introduction to ASP.NET MVC
 
Single Page Applications in SharePoint with Angular
Single Page Applications in SharePoint with AngularSingle Page Applications in SharePoint with Angular
Single Page Applications in SharePoint with Angular
 
Why I am hooked on the future of React
Why I am hooked on the future of ReactWhy I am hooked on the future of React
Why I am hooked on the future of React
 
Angular 4
Angular 4Angular 4
Angular 4
 
An afternoon with angular 2
An afternoon with angular 2An afternoon with angular 2
An afternoon with angular 2
 
SPA, Scalable Application & AngularJS
SPA, Scalable Application & AngularJSSPA, Scalable Application & AngularJS
SPA, Scalable Application & AngularJS
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Angularjs
AngularjsAngularjs
Angularjs
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance Testing
 
Protractor training
Protractor trainingProtractor training
Protractor training
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Angular js for Beginnners
Angular js for BeginnnersAngular js for Beginnners
Angular js for Beginnners
 

En vedette

Angle Forward with TypeScript
Angle Forward with TypeScriptAngle Forward with TypeScript
Angle Forward with TypeScriptJeremy Likness
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Jeremy Likness
 
The Windows Runtime and the Web
The Windows Runtime and the WebThe Windows Runtime and the Web
The Windows Runtime and the WebJeremy Likness
 
My XML is Alive! An Intro to XAML
My XML is Alive! An Intro to XAMLMy XML is Alive! An Intro to XAML
My XML is Alive! An Intro to XAMLJeremy Likness
 
Back to the ng2 Future
Back to the ng2 FutureBack to the ng2 Future
Back to the ng2 FutureJeremy Likness
 
Cross-Platform Agile DevOps with Visual Studio Team Services
Cross-Platform Agile DevOps with Visual Studio Team ServicesCross-Platform Agile DevOps with Visual Studio Team Services
Cross-Platform Agile DevOps with Visual Studio Team ServicesJeremy Likness
 

En vedette (8)

Angle Forward with TypeScript
Angle Forward with TypeScriptAngle Forward with TypeScript
Angle Forward with TypeScript
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
 
The Windows Runtime and the Web
The Windows Runtime and the WebThe Windows Runtime and the Web
The Windows Runtime and the Web
 
Windows 8.1 Sockets
Windows 8.1 SocketsWindows 8.1 Sockets
Windows 8.1 Sockets
 
My XML is Alive! An Intro to XAML
My XML is Alive! An Intro to XAMLMy XML is Alive! An Intro to XAML
My XML is Alive! An Intro to XAML
 
Enterprise TypeScript
Enterprise TypeScriptEnterprise TypeScript
Enterprise TypeScript
 
Back to the ng2 Future
Back to the ng2 FutureBack to the ng2 Future
Back to the ng2 Future
 
Cross-Platform Agile DevOps with Visual Studio Team Services
Cross-Platform Agile DevOps with Visual Studio Team ServicesCross-Platform Agile DevOps with Visual Studio Team Services
Cross-Platform Agile DevOps with Visual Studio Team Services
 

Similaire à C# Async/Await Explained

Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)Panagiotis Kanavos
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)Panagiotis Kanavos
 
Real time system_performance_mon
Real time system_performance_monReal time system_performance_mon
Real time system_performance_monTomas Doran
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenixJared Smith
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threadsmperham
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Hannes Lowette
 
Repeating History...On Purpose...with Elixir
Repeating History...On Purpose...with ElixirRepeating History...On Purpose...with Elixir
Repeating History...On Purpose...with ElixirBarry Jones
 
Asynchronous programming using CompletableFutures in Java
Asynchronous programming using CompletableFutures in JavaAsynchronous programming using CompletableFutures in Java
Asynchronous programming using CompletableFutures in JavaOresztész Margaritisz
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Hannes Lowette
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Martijn Verburg
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in JavaLukas Steinbrecher
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)Tech in Asia ID
 

Similaire à C# Async/Await Explained (20)

Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
 
Real time system_performance_mon
Real time system_performance_monReal time system_performance_mon
Real time system_performance_mon
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenix
 
Gpgpu intro
Gpgpu introGpgpu intro
Gpgpu intro
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Repeating History...On Purpose...with Elixir
Repeating History...On Purpose...with ElixirRepeating History...On Purpose...with Elixir
Repeating History...On Purpose...with Elixir
 
Node.js primer
Node.js primerNode.js primer
Node.js primer
 
Asynchronous programming using CompletableFutures in Java
Asynchronous programming using CompletableFutures in JavaAsynchronous programming using CompletableFutures in Java
Asynchronous programming using CompletableFutures in Java
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
Scalable game-servers-tgc
Scalable game-servers-tgcScalable game-servers-tgc
Scalable game-servers-tgc
 
Perl in Teh Cloud
Perl in Teh CloudPerl in Teh Cloud
Perl in Teh Cloud
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
 
A first look into the Project Loom in Java
A first look into the Project Loom in JavaA first look into the Project Loom in Java
A first look into the Project Loom in Java
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 

Dernier

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
[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
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Dernier (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[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
 
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
 
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...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

C# Async/Await Explained

  • 1. Your Cloud. Your Business. C# Async and Await Explained Jeremy Likness Principal Architect @JeremyLikness
  • 2. Our Mission, Vision, and Values
  • 4. TODAY’S AGENDA 1. Why? Why do we need new keywords? 2. What? What exactly do async and await do? 3. How? How and when should async and await be used? 4. Q&A You have questions, I have answers
  • 6. WHY? Fundamentals • Once upon a time, an OS was created to run apps • These apps would run in a process • Processes would be segregated into app domains • App domains would run threads Process App Domain 1 •Thread 1 •Thread 2 App Domain 2 •Thread 3 •Thread 4 • Process is the running program, i.e. the .NET CLR host • App domains provide isolation from each other and can be uniquely configured, loaded, unloaded, and secured • Threads enable management of code execution
  • 7. WHY? What’s in every thread … Thread kernel object (context) ~1KB Thread environment block (local storage data, graphics, exception handling) ~4KB – 8KB User mode stack ~1MB Kernel mode stack ~20KB
  • 8. WHY? The life of one thread… Initialize memory Thread attach notifications sent to every DLL in the process Execute code Context Switch Execute Code Thread detach notifications Deallocate memory
  • 10. WHY? And to think …
  • 12. WHY? A Dip in the Thread Pool • We agree threads have overhead • To address this, the CLR introduces the thread pool • Starts out empty • As tasks are dispatched, threads are created • When thread is done, it is returned to the pool and recycled • Trade-offs exist: • Less overhead (memory pressure) • Less time to allocate/spin up a thread • However, fewer threads are scheduled concurrently
  • 14. WHY? Tasks • Make it easier to deal with threads and the thread pool • Easy to wait • Automatic ability to cancel • Simple access to result • Chainable tasks (one starts when the other finishes) • Child tasks • Parallel functions
  • 16. WHY? I/O Operations I/O Request Packet Make I/O Request Device Driver Queue Driver Does I/O Thread Goes to Sleep Thread Wakes Up
  • 17. WHY? Synchronous: Two Threads Handle Request Blocked I/O Complete Handle Request Blocked I/O Complete
  • 18. WHY? Asynchronous: One Thread Handle Request CompleteHandle Request Complete Asynchronous Asynchronous
  • 20. WHAT?
  • 21. What? async • Expecting to use await • Does not create new thread, always uses same thread as caller • After await may or may not use same thread (thread pool is involved, so threads are reusable) • If a SynchronizationContet exists, it will return to that thread • You can also modify this behavior using ConfigureAwait • Basically … think “yield” for threads!
  • 22. What? Yield: a refresher
  • 24. Best Practices • Never async void (use Task instead) • Exceptions can’t be caught so they are thrown in the context (if you have one!) • Made specifically for event handlers • If you must use for event handler, try to isolate the majority of code in another await that does return a Task • Never mix async and blocking code together • Task.Wait, Task.Result are generally bad ideas • Exception is a console application • From the necessary static main, promote to an async static main with a wait • Task.Wait should become Task.When
  • 25. HOW?
  • 26. How? • More impactful for I/O bound than compute-bound • Remember the Fibonacci examples? • Check this out …
  • 28. How? • “I usually don’t work with multi-threading” • If you are working on the web, you are in a multi-threaded environment • If you are I/O bound, you should take advantage • Entity Framework now supports asynchronous methods! • The transformation is simple …
  • 30. How? Real World Results Source: http://blog.stevensanderson.com/2010/01/
  • 31. How? Windows 8.x / 10 or whatever • Windows Runtime (WinRT) • IAsyncInfo • IAsyncAction • IAsyncOperation<TResult> • IAsyncActionWithProgress<TProgress> • IAsyncOperationWithProgress<TResult, TProgress> • ThreadPool.RunAsync • IAsyncInfo.AsTask()
  • 32. Recap • You are always working with multi-threaded, don’t sell yourself short! • Compute-bound does not benefit as much from asynchronous as you might think, except to free the main context (typically your UI thread) • I/O has tremendous benefits • Async does not spin up a new thread. Instead, it establishes a state machine and makes the thread reusable and re- entrant • Await is not like Wait() because it doesn’t block and it allows you to recycle threads • If you have async I/O then USE IT! Async Task<> is your friend.

Notes de l'éditeur

  1. 01Threads
  2. 02ManyTasksNoThreadPool, 03ManyThreadsThreadPool
  3. 04Tasks, 05Parallel
  4. 06Asynchronous
  5. 07AsyncAwait, 07bAsyncAwaitWithContext, 08NoAsyncAwait
  6. 09AsyncThreadPool