Asynchronous Programming
Tips and Tricks in .NET
Tugberk Ugurlu
tugberkugurlu.com
@tourismgeek
Slide 2
Slide 2 text
Agenda
• Refresh on Asynchronous Programming Models on .NET
• High level overview of async/await keywords
• Tips and Tricks on TPL + async/await usage and scenarios
Slide 3
Slide 3 text
Assumptions
• Knowledge on C# (duh!)
• Prior Knowledge on Asynchronous Programming
• Prior Knowledge on TPL (Task Parallel Library)
Slide 4
Slide 4 text
No content
Slide 5
Slide 5 text
Asynchronous Programming Models in .NET
• Asynchronous Programming Model (APM)
• Event-based Asynchronous Pattern (EAP)
• Task-Based Asynchronous Pattern (TAP)
Slide 6
Slide 6 text
Asynchronous Programming Model (APM)
Slide 7
Slide 7 text
Event-based Asynchronous Pattern (EAP)
Slide 8
Slide 8 text
Task-Based Asynchronous Pattern (TAP)
Slide 9
Slide 9 text
async/await and its glory
Slide 10
Slide 10 text
async/await and its glory
For more information, check out: "Easy Asynchrony with C#: No More
Callbacks! (http://bit.ly/1FEoK85)" talk by Mads Torgersen
Slide 11
Slide 11 text
Make Use of Pre Completed Tasks
Slide 12
Slide 12 text
Make Use of Pre Completed Tasks
DON’T
Slide 13
Slide 13 text
Make Use of Pre Completed Tasks
DON’T
Slide 14
Slide 14 text
Make Use of Pre Completed Tasks
DO
Slide 15
Slide 15 text
Make Use of Pre Completed Tasks
DO
Slide 16
Slide 16 text
DON’T await on Task.FromResult
Slide 17
Slide 17 text
DON’T await on Task.FromResult
DON’T
Slide 18
Slide 18 text
Directly Return the Task
“Generally, if you are not going to be running any continuation in a
method which consumes a Task returning code, don’t await on the
Task”
Slide 19
Slide 19 text
Directly Return the Task
DON’T
Slide 20
Slide 20 text
Directly Return the Task
DO
Slide 21
Slide 21 text
Don’t Wrap Thread Offloading Work
“Library methods should not lie. If it looks async in its signature, it
should be async in its implementation.”
- Lucian Wischik
https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-Library-Methods-Shouldn-t-Lie
ConfigureAwait(false)
General rule of thumb:
“When you are awaiting inside a library code, you should never care
about SynchronizationContext and call ConfigureAwait(false)”
Slide 25
Slide 25 text
ConfigureAwait(false)
DON’T
Slide 26
Slide 26 text
Task.WhenAll(Task[])
Slide 27
Slide 27 text
Task.WhenAll(Task[])
“Be careful on how you do parallelization on server, refer to "How and
Where Concurrent Asynchronous I/O with ASP.NET Web API
(http://bit.ly/1NwGp5I)" for more information about this”
Slide 28
Slide 28 text
There are MORE!
• Six Essential Tips for Async: http://bit.ly/1ynpoEm
• Async best practices: http://bit.ly/1DsFuMi
• Async Performance: http://bit.ly/1EqWYdy
• My Async Blog Posts: http://tugberkugurlu.com/tags/async
• The zen of async: http://bit.ly/1NyIdvb