SlideShare a Scribd company logo
Demystifying Asynchronous
Programming in .NET
What is asynchronous programming
- Unit of work running separately from its caller.
- Common implementations: promises and callbacks.
Asynchronous == Parallelism?
Yes. No. Well, sort of.
Parallelism can happen with the TPL although it’s not the goal.
Parallelism -> splitting a task into smaller pieces to execute them concurrently.
Task Parallel Library (TPL)
● Includes asynchronous and parallelism APIs (Task, Parallel LINQ).
● Gotcha: although being in the .NET CLR, F# uses a completely distinct
implementation.
● Mostly about Task and the underlying plumbing.
● async/await is the language mechanism to generate the code around Tasks for
continuations
In C#
async Task<String> GetContent(String url)
{
return await _httpClient.GetAsync(url);
}
C# 5
.NET 4.5
F# Async
Distinct implementation, predates the TPL.
let sleep milliseconds message: WebPart =
fun (x : HttpContext) ->
async {
do! Async.Sleep milliseconds
return! OK message x
}
Non blocking I/O
- Non blocking I/O is commonly implied in .NET when talking about async/await
and the TPL.
- Similar to NodeJs, same purpose to run many requests on few threads
- Many of the .NET async APIs use async IO, such as ADO.NET
Non blocking I/O in Operating systems
● Known as overlapped I/O in Windows
● Posix AIO in Linux
● Socket AIO has arguably the most impact in web apps (database calls, HTTP, etc.)
Example: Dapper queries
SqlConnection.Query() -> synchronous socket. Synchronous blocking
SqlConnection.QueryAsync() -> asynchronous socket. Asynchrounous non blocking
Task.Run(() => SqlConnection.Query() -> still a synchronous socket) Asynchrounous
blocking.
SqlConnection.QueryAsync().Result -> Asynchronous call and blocks the current
thread
Why all the fuss about asynchronous anyway
(Supposing asynchronous IO)
● Scalability, handling many requests in parallel
● Better handling of spikes. .NET throttle thread creation at 1 per half second.
Async regardless of IO
● Freeing the UI thread in a desktop application
● Asynchronous flows
Async all the things
Not so fast
- Need to propagate the async all the way up to the caller
- Overhead on pure CPU code
- Exception handling is tricky.
- Not meant for fire and forget. Hard to debug, monitor, error handling.
You can block on async code. Don’t.
Task.Result -> Congratulations, it’s a deadlock (probably)
Blocking -> the async IO is now synchronous.
Frameworks such as ASP.NET force a request to continue on the same thread.
Doesn’t happen anymore in ASP.NET Core, no synchronization context.
State machine
● The async/await is replaced with a state machine by the compiler
● Async/await is a language construct -> doesn’t exist in IL.
● Could be done manually, lot of boilerplate
Quiz
var tasks = Enumerable.Range(0, 100).Select(async _ => await
Task.Delay(1000)).ToArray();
var tasks = Enumerable.Range(0, 100).Select(async _ => await Task.Run(() =>
Thread.Sleep(1000))).ToArray();
Task.WaitAll(tasks);
async _ => await Task.Delay(1000)
async _ => await Task.Run(() => Thread.Sleep(1000))
Beware of background processing
Easy to fire and forget -> doesn’t mean you should
- Error handling is thrown out the window
- No priority on what is executed
- No way of cancelling anything
- Hell to monitor/debug
- Accessing thread scoped dependencies and all hell breaks loose.
- Hangfire is a worthy alternative.
Cancellation
● Cancellation token to cancel a task
● Essentially throws an exception, bubbling up the call chain
● Useful for cleanup of resources or stop intensive processing
var tokenSource = new CancellationTokenSource();
var task = _httpClient..GetAsync("http://www.google.com", cts.Token);
tokenSource.Cancel();
Takeaways
● Non-blocking I/O is usually implied with async in .NET
● Asynchronous programming has many benefits but shouldn’t be used for all
methods.
● Blocking on async code essentially nullifies all gain, if you’re lucky. Use await!
● If you’re not lucky, deadlock
Questions?
Twitter: @plmaheu

More Related Content

PPTX
Async Programming in C# 5
PPTX
Asynchronous programming in C#
PPTX
Asynchronous programming - .NET Way
PPT
Asynchronous Programming in C# - Part 1
PDF
Test Automation
PPT
Introduction to the Web API
PPTX
Async programming in c#
PDF
Karate - powerful and simple framework for REST API automation testing
Async Programming in C# 5
Asynchronous programming in C#
Asynchronous programming - .NET Way
Asynchronous Programming in C# - Part 1
Test Automation
Introduction to the Web API
Async programming in c#
Karate - powerful and simple framework for REST API automation testing

What's hot (20)

PPTX
Api testing
PPTX
Introduction to Gitlab | Gitlab 101 | Training Session
ODP
API Testing With Katalon Studio
PDF
REST API Best (Recommended) Practices
PPT
White box testing-200709
PPTX
Solid principles
PPTX
Asynchronous programming
PPTX
ASP.NET Web API
PDF
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
PDF
Angular
PPTX
REST-API introduction for developers
PDF
Automation Best Practices
PDF
Từ GĂ  Đáșżn Pro Git vĂ  GitHub trong 60 phĂșt
PDF
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
PDF
Data Grids with Oracle Coherence
PDF
Primeiros passos com a API do Zabbix - Webinar JLCP
PDF
TestingUY 2019. Patrones de diseño en la automatización PageObject o ScreenPlay.
PPT
SOLID Design Principles
PDF
Hacking Adobe Experience Manager sites
PPTX
Dev ops != Dev+Ops
Api testing
Introduction to Gitlab | Gitlab 101 | Training Session
API Testing With Katalon Studio
REST API Best (Recommended) Practices
White box testing-200709
Solid principles
Asynchronous programming
ASP.NET Web API
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
Angular
REST-API introduction for developers
Automation Best Practices
Từ GĂ  Đáșżn Pro Git vĂ  GitHub trong 60 phĂșt
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Data Grids with Oracle Coherence
Primeiros passos com a API do Zabbix - Webinar JLCP
TestingUY 2019. Patrones de diseño en la automatización PageObject o ScreenPlay.
SOLID Design Principles
Hacking Adobe Experience Manager sites
Dev ops != Dev+Ops
Ad

Similar to Asynchronous Programming in .NET (20)

PPTX
Task parallel library presentation
PPTX
Training – Going Async
PDF
The art of concurrent programming
PPTX
C# 5 deep drive into asynchronous programming
PPTX
AsynchronousProgrammingDesignPatterns.pptx
PDF
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
PPTX
Ddd melbourne 2011 C# async ctp
PDF
Async Await for Mobile Apps
PDF
.Net Multithreading and Parallelization
PDF
Rundown of Async/Await in Rust
PDF
Async/Await Best Practices
PPTX
Sync with async
PPTX
End to-end async and await
 
PPTX
Async and Await on the Server
PDF
Deep Dive async/await in Unity with UniTask(EN)
PPTX
PDF
PyCon Canada 2019 - Introduction to Asynchronous Programming
PDF
Concurrecny inf sharp
PDF
Javascript internals
PPSX
Async-await best practices in 10 minutes
Task parallel library presentation
Training – Going Async
The art of concurrent programming
C# 5 deep drive into asynchronous programming
AsynchronousProgrammingDesignPatterns.pptx
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Ddd melbourne 2011 C# async ctp
Async Await for Mobile Apps
.Net Multithreading and Parallelization
Rundown of Async/Await in Rust
Async/Await Best Practices
Sync with async
End to-end async and await
 
Async and Await on the Server
Deep Dive async/await in Unity with UniTask(EN)
PyCon Canada 2019 - Introduction to Asynchronous Programming
Concurrecny inf sharp
Javascript internals
Async-await best practices in 10 minutes
Ad

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
System and Network Administration Chapter 2
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
history of c programming in notes for students .pptx
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Transform Your Business with a Software ERP System
PDF
How Creative Agencies Leverage Project Management Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Design an Analysis of Algorithms II-SECS-1021-03
System and Network Administration Chapter 2
Online Work Permit System for Fast Permit Processing
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Upgrade and Innovation Strategies for SAP ERP Customers
Design an Analysis of Algorithms I-SECS-1021-03
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
How to Choose the Right IT Partner for Your Business in Malaysia
Wondershare Filmora 15 Crack With Activation Key [2025
Softaken Excel to vCard Converter Software.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
history of c programming in notes for students .pptx
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Odoo POS Development Services by CandidRoot Solutions
Transform Your Business with a Software ERP System
How Creative Agencies Leverage Project Management Software.pdf

Asynchronous Programming in .NET

  • 2. What is asynchronous programming - Unit of work running separately from its caller. - Common implementations: promises and callbacks.
  • 3. Asynchronous == Parallelism? Yes. No. Well, sort of. Parallelism can happen with the TPL although it’s not the goal. Parallelism -> splitting a task into smaller pieces to execute them concurrently.
  • 4. Task Parallel Library (TPL) ● Includes asynchronous and parallelism APIs (Task, Parallel LINQ). ● Gotcha: although being in the .NET CLR, F# uses a completely distinct implementation. ● Mostly about Task and the underlying plumbing. ● async/await is the language mechanism to generate the code around Tasks for continuations
  • 5. In C# async Task<String> GetContent(String url) { return await _httpClient.GetAsync(url); } C# 5 .NET 4.5
  • 6. F# Async Distinct implementation, predates the TPL. let sleep milliseconds message: WebPart = fun (x : HttpContext) -> async { do! Async.Sleep milliseconds return! OK message x }
  • 7. Non blocking I/O - Non blocking I/O is commonly implied in .NET when talking about async/await and the TPL. - Similar to NodeJs, same purpose to run many requests on few threads - Many of the .NET async APIs use async IO, such as ADO.NET
  • 8. Non blocking I/O in Operating systems ● Known as overlapped I/O in Windows ● Posix AIO in Linux ● Socket AIO has arguably the most impact in web apps (database calls, HTTP, etc.)
  • 9. Example: Dapper queries SqlConnection.Query() -> synchronous socket. Synchronous blocking SqlConnection.QueryAsync() -> asynchronous socket. Asynchrounous non blocking Task.Run(() => SqlConnection.Query() -> still a synchronous socket) Asynchrounous blocking. SqlConnection.QueryAsync().Result -> Asynchronous call and blocks the current thread
  • 10. Why all the fuss about asynchronous anyway (Supposing asynchronous IO) ● Scalability, handling many requests in parallel ● Better handling of spikes. .NET throttle thread creation at 1 per half second. Async regardless of IO ● Freeing the UI thread in a desktop application ● Asynchronous flows
  • 11. Async all the things
  • 12. Not so fast - Need to propagate the async all the way up to the caller - Overhead on pure CPU code - Exception handling is tricky. - Not meant for fire and forget. Hard to debug, monitor, error handling.
  • 13. You can block on async code. Don’t. Task.Result -> Congratulations, it’s a deadlock (probably) Blocking -> the async IO is now synchronous. Frameworks such as ASP.NET force a request to continue on the same thread. Doesn’t happen anymore in ASP.NET Core, no synchronization context.
  • 14. State machine ● The async/await is replaced with a state machine by the compiler ● Async/await is a language construct -> doesn’t exist in IL. ● Could be done manually, lot of boilerplate
  • 15. Quiz var tasks = Enumerable.Range(0, 100).Select(async _ => await Task.Delay(1000)).ToArray(); var tasks = Enumerable.Range(0, 100).Select(async _ => await Task.Run(() => Thread.Sleep(1000))).ToArray(); Task.WaitAll(tasks);
  • 16. async _ => await Task.Delay(1000)
  • 17. async _ => await Task.Run(() => Thread.Sleep(1000))
  • 18. Beware of background processing Easy to fire and forget -> doesn’t mean you should - Error handling is thrown out the window - No priority on what is executed - No way of cancelling anything - Hell to monitor/debug - Accessing thread scoped dependencies and all hell breaks loose. - Hangfire is a worthy alternative.
  • 19. Cancellation ● Cancellation token to cancel a task ● Essentially throws an exception, bubbling up the call chain ● Useful for cleanup of resources or stop intensive processing var tokenSource = new CancellationTokenSource(); var task = _httpClient..GetAsync("http://www.google.com", cts.Token); tokenSource.Cancel();
  • 20. Takeaways ● Non-blocking I/O is usually implied with async in .NET ● Asynchronous programming has many benefits but shouldn’t be used for all methods. ● Blocking on async code essentially nullifies all gain, if you’re lucky. Use await! ● If you’re not lucky, deadlock

Editor's Notes

  • #3: Sending an email and doing something else while waiting for an answer.
  • #14: Code that works in a console application but deadlocks in an ASP.NET application SynchronizationContext -> https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
  • #15: https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-1-compilation
  • #16: Around a second for Task.Delay Around 12 seconds Task.Run
  • #19: The list goes on. At the very have an executor class so you can refactor later without having to hunt for all Task.Run calls. Memes: Jurassic Park, because you could doesn’t mean you should Friends don’t let each other Task.Run()
  • #20: Cancellation token