SlideShare a Scribd company logo
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/

More Related Content

PPTX
Advanced AngularJS Tips and Tricks
PPTX
Angular from a Different Angle
PPTX
Let's Build an Angular App!
PPTX
Introduction of ASP.NET MVC and AngularJS
PPTX
Valentine with Angular js - Introduction
PPTX
Better End-to-End Testing with Page Objects Model using Protractor
PPTX
Introduction to Angular 2
PDF
Using JHipster for generating Angular/Spring Boot apps
Advanced AngularJS Tips and Tricks
Angular from a Different Angle
Let's Build an Angular App!
Introduction of ASP.NET MVC and AngularJS
Valentine with Angular js - Introduction
Better End-to-End Testing with Page Objects Model using Protractor
Introduction to Angular 2
Using JHipster for generating Angular/Spring Boot apps

What's hot (20)

PDF
Reactive Thinking in Java with RxJava2
PPTX
Saving Time By Testing With Jest
PPT
Intro to Service Worker API and its use cases
PPTX
Angular Unit Testing
PPTX
Angular js
PPTX
SharePoint Framework, Angular and Azure Functions
PDF
Using JHipster for generating Angular/Spring Boot apps
PPTX
Fast Track introduction to ASP.NET MVC
PPTX
Single Page Applications in SharePoint with Angular
PPTX
Why I am hooked on the future of React
PPTX
Angular 4
PPTX
An afternoon with angular 2
PDF
SPA, Scalable Application & AngularJS
PDF
Introduction to Angular 2
ODP
Angularjs
PDF
Angular2 Development for Java developers
PPT
Integration and Acceptance Testing
PPTX
Protractor training
PDF
Overview of the AngularJS framework
PPTX
Angular js for Beginnners
Reactive Thinking in Java with RxJava2
Saving Time By Testing With Jest
Intro to Service Worker API and its use cases
Angular Unit Testing
Angular js
SharePoint Framework, Angular and Azure Functions
Using JHipster for generating Angular/Spring Boot apps
Fast Track introduction to ASP.NET MVC
Single Page Applications in SharePoint with Angular
Why I am hooked on the future of React
Angular 4
An afternoon with angular 2
SPA, Scalable Application & AngularJS
Introduction to Angular 2
Angularjs
Angular2 Development for Java developers
Integration and Acceptance Testing
Protractor training
Overview of the AngularJS framework
Angular js for Beginnners
Ad

Viewers also liked (8)

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

Similar to C# Async/Await Explained (20)

PPTX
Async and Await on the Server
PPTX
Asynchronous programming - .NET Way
PPTX
Task parallel library presentation
PDF
Why async matters
PDF
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
PPTX
Async/Await
PDF
Async Await for Mobile Apps
PPTX
Async await
PPTX
End to-end async and await
PPTX
Async programming in c#
PDF
Async await...oh wait!
PPTX
Training – Going Async
PDF
Concurrency and parallel in .net
PPTX
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
PPSX
Async-await best practices in 10 minutes
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
PDF
I see deadlocks : Matt Ellis - Techorama NL 2024
PPTX
C# 5 deep drive into asynchronous programming
PPTX
MobConf - session on C# async-await on 18june2016 at Kochi
PDF
Webcast: Asynchronous Programming Demystified
Async and Await on the Server
Asynchronous programming - .NET Way
Task parallel library presentation
Why async matters
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
Async/Await
Async Await for Mobile Apps
Async await
End to-end async and await
Async programming in c#
Async await...oh wait!
Training – Going Async
Concurrency and parallel in .net
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Async-await best practices in 10 minutes
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
I see deadlocks : Matt Ellis - Techorama NL 2024
C# 5 deep drive into asynchronous programming
MobConf - session on C# async-await on 18june2016 at Kochi
Webcast: Asynchronous Programming Demystified

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PPTX
A Presentation on Artificial Intelligence
PPT
Teaching material agriculture food technology
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Machine learning based COVID-19 study performance prediction
PDF
Electronic commerce courselecture one. Pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Modernizing your data center with Dell and AMD
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
KodekX | Application Modernization Development
A Presentation on Artificial Intelligence
Teaching material agriculture food technology
NewMind AI Weekly Chronicles - August'25 Week I
Unlocking AI with Model Context Protocol (MCP)
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Review of recent advances in non-invasive hemoglobin estimation
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Machine learning based COVID-19 study performance prediction
Electronic commerce courselecture one. Pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
Modernizing your data center with Dell and AMD
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
MYSQL Presentation for SQL database connectivity
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf

C# Async/Await Explained

Editor's Notes

  • #12: 01Threads
  • #14: 02ManyTasksNoThreadPool, 03ManyThreadsThreadPool
  • #16: 04Tasks, 05Parallel
  • #20: 06Asynchronous
  • #24: 07AsyncAwait, 07bAsyncAwaitWithContext, 08NoAsyncAwait
  • #28: 09AsyncThreadPool