SlideShare ist ein Scribd-Unternehmen logo
1 von 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/

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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)
 

Kürzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
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
 
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
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
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 future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
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 future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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.

Hinweis der Redaktion

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