SlideShare a Scribd company logo
Deceptive simplicity of async and await
WIN387
Andrei Marukovich
lunarfrog.com
@amarukovich
Looks familiar?
Deceptive simplicity of async and await
• Application errors
• Using the UI thread for performing long operations
UI unresponsiveness
Deceptive simplicity of async and await
Deceptive simplicity of async and await
Synchronous method
private void ButtonClick(object sender, EventArgs e)
{
WebClient client = new WebClient();
var imageData = client.DownloadData(“http://image-url”);
pictureBox.Image = Image.FromStream(new MemoryStream(imageData));
}
Deceptive simplicity of async and await
Asynchronous method
private async void ButtonClick(object sender, EventArgs e)
{
WebClient client = new WebClient();
var imageData = await client.DownloadDataTaskAsync(“http://image-url”);
pictureBox.Image = Image.FromStream(new MemoryStream(imageData));
}
Deceptive simplicity of async and await
Asynchronous method
private async void ButtonClick(object sender, EventArgs e)
{
WebClient client = new WebClient();
var imageData = await client.DownloadDataTaskAsync(“http://image-url”);
pictureBox.Image = Image.FromStream(new MemoryStream(imageData));
var strData = await client.DownloadStringTaskAsync(“http://str-url”);
// …
}
Every API which might take more than 50ms
should be async
WinRT
Deceptive simplicity of async and await
Deceptive simplicity of async and await
Demo
WinRT and async
Deep dive
Deceptive simplicity of async and await
static void Main(string[] args)
{
DoSomething();
}
static void DoSomething()
{
// method body
}
static void Main(string[] args)
{
DoSomething();
}
async static Task DoSomething()
{
// method body
}
Deep dive
Deceptive simplicity of async and await
State machine
Deceptive simplicity of async and await
struct DoSomethingStruct : IAsyncStateMachine
{
// Argument and local variables
public Int32 x;
// Compiler-generated variables
public Int32 _state;
public AsyncTaskMethodBuilder _builder;
void MoveNext() { … }
}
MoveNext()
Deceptive simplicity of async and await
void MoveNext() {
try {
switch(_state) {
// modified method body
}
}
catch (Exception exception) {
_builder.SetException(exception);
return;
}
_builder.SetResult();
}
Async function transformation
Deceptive simplicity of async and await
static Task DoSomething()
{
var stateMachine = new DoSomethingStruct();
stateMachine._builder = AsyncTaskMethodBuilder.Create();
stateMachine._state = -1;
stateMachine._builder.Start(stateMachine);
return stateMachine._builder.Task;
}
Using await
Deceptive simplicity of async and await
await DoSomething();
Task task = DoSomething();
INotifyCompletion awaiter = task.GetAwaiter();
if (!awaiter.IsCompleted) {
awaiter.OnCompleted(continue_delegate)
}
Bringing it all together
async Task Method1()
{
await Method2();
}
async Task Method2()
{
await _file.CopyAsync(_folder, _name);
}
Bringing it all together
Method1
Method2
Task
CopyAsync
Copy
Task Method2
Method1
Defining async methods
async Task Method1()
{
}
async Task<StorageFolder> Method2()
{
return ApplicationData.Current.LocalFolder;
}
async void button1_Click(object sender, EventArgs e)
{
}
Avoid async void as much as possible
Deceptive simplicity of async and await
Demo
async void and error handling
Deceptive simplicity of async and await
async lambdas
obj.Handle( async () => { await Task.Delay(1000); } );
Deceptive simplicity of async and await
void Handle(Func<Task> action);
Func<Task> f = async () => { await Task.Delay(1000); }
void Handle(Action action);
Action a = async () => { await Task.Delay(1000); }
IL: AsyncTaskMethodBuilder
IL: AsyncVoidMethodBuilder
Demo
More async in WinRT
Deceptive simplicity of async and await
Constrains
• Cannot use await inside constructor and property accessor
• Cannot use await inside catch and finally
• Cannot use await inside lock block
• Cannot use await inside Main method
• An async method cannot have a ref or out parameters
What to take away
• async/await are not magic
• Always await your async operations
• async void methods are only suited for UI event handlers
• Be careful around async void and exceptions
• Be aware of deferral classes in WinRT
Next steps
• Parallel Programming team blog
 http://bit.ly/pfxteam
• Deeper into Async and Await, Kathleen Dollard
 ARC319
• Three Essential Tips for Async (video)
 http://bit.ly/AsyncTips
• Async for .NET 4.0 and Windows Phone (NuGet)
 http://bit.ly/AsyncNet4

More Related Content

What's hot (20)

PPTX
Avoiding Callback Hell with Async.js
cacois
 
PDF
JavaScript promise
eslam_me
 
PPTX
Introduction to Jquery
Ahmed Elharouny
 
PPTX
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
PPTX
J Query Presentation of David
Arun David Johnson R
 
PPTX
Advanced Jquery
Ahmed Elharouny
 
PPTX
Async Programming with C#5: Basics and Pitfalls
EastBanc Tachnologies
 
PDF
JavaScript Promises
Tomasz Bak
 
PPTX
Workers
Adrian Caetano
 
PPT
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
PPTX
JavaScript Promises
L&T Technology Services Limited
 
PDF
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Islam Sharabash
 
PPTX
Async best practices DotNet Conference 2016
Lluis Franco
 
PPTX
Async Best Practices
Lluis Franco
 
PDF
Javascript Promises/Q Library
async_io
 
PPTX
Promises, promises, and then observables
Stefan Charsley
 
PDF
Asynchronous programming done right - Node.js
Piotr Pelczar
 
PDF
NestJS
Wilson Su
 
PDF
Angular and The Case for RxJS
Sandi Barr
 
PDF
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Avoiding Callback Hell with Async.js
cacois
 
JavaScript promise
eslam_me
 
Introduction to Jquery
Ahmed Elharouny
 
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
J Query Presentation of David
Arun David Johnson R
 
Advanced Jquery
Ahmed Elharouny
 
Async Programming with C#5: Basics and Pitfalls
EastBanc Tachnologies
 
JavaScript Promises
Tomasz Bak
 
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
JavaScript Promises
L&T Technology Services Limited
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Islam Sharabash
 
Async best practices DotNet Conference 2016
Lluis Franco
 
Async Best Practices
Lluis Franco
 
Javascript Promises/Q Library
async_io
 
Promises, promises, and then observables
Stefan Charsley
 
Asynchronous programming done right - Node.js
Piotr Pelczar
 
NestJS
Wilson Su
 
Angular and The Case for RxJS
Sandi Barr
 
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 

Similar to Deceptive simplicity of async and await (20)

DOCX
Experienced Selenium Interview questions
archana singh
 
PDF
rx.js make async programming simpler
Alexander Mostovenko
 
PDF
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
PPTX
Ondemand scaling-aws
Iegor Fadieiev
 
PDF
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
PDF
Rxjs kyivjs 2015
Alexander Mostovenko
 
PDF
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
PPTX
Don't Wait! Develop Responsive Applications with Java EE7 Instead
WASdev Community
 
PDF
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
ODP
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
PDF
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
PDF
Javascript #8 : événements
Jean Michel
 
PDF
Promises look into the async future
slicejs
 
PDF
Multithreading on iOS
Make School
 
PDF
From Node.js to Design Patterns
Luciano Mammino
 
PPTX
Reactive programming every day
Vadym Khondar
 
PDF
Modern Android app library stack
Tomáš Kypta
 
PPTX
Christophe Spring Actionscript Flex Java Exchange
Skills Matter
 
PPTX
Ordina SOFTC Presentation - Async CTP
Ordina Belgium
 
PPTX
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Experienced Selenium Interview questions
archana singh
 
rx.js make async programming simpler
Alexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
Ondemand scaling-aws
Iegor Fadieiev
 
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Rxjs kyivjs 2015
Alexander Mostovenko
 
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
WASdev Community
 
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
Javascript #8 : événements
Jean Michel
 
Promises look into the async future
slicejs
 
Multithreading on iOS
Make School
 
From Node.js to Design Patterns
Luciano Mammino
 
Reactive programming every day
Vadym Khondar
 
Modern Android app library stack
Tomáš Kypta
 
Christophe Spring Actionscript Flex Java Exchange
Skills Matter
 
Ordina SOFTC Presentation - Async CTP
Ordina Belgium
 
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Ad

More from Andrei Marukovich (8)

PPTX
Modern .NET Ecosystem
Andrei Marukovich
 
PPTX
Using NuGet libraries in your application
Andrei Marukovich
 
PPTX
C# code sharing across the platforms
Andrei Marukovich
 
PPTX
Open Source Libraries for.NET developers
Andrei Marukovich
 
PPTX
Reactive Extensions for .NET
Andrei Marukovich
 
PPTX
All about data persistence in Windows 8
Andrei Marukovich
 
PPTX
ATDD in practice
Andrei Marukovich
 
PPTX
A Developer's View of Windows 8
Andrei Marukovich
 
Modern .NET Ecosystem
Andrei Marukovich
 
Using NuGet libraries in your application
Andrei Marukovich
 
C# code sharing across the platforms
Andrei Marukovich
 
Open Source Libraries for.NET developers
Andrei Marukovich
 
Reactive Extensions for .NET
Andrei Marukovich
 
All about data persistence in Windows 8
Andrei Marukovich
 
ATDD in practice
Andrei Marukovich
 
A Developer's View of Windows 8
Andrei Marukovich
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
July Patch Tuesday
Ivanti
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

Deceptive simplicity of async and await

  • 1. Deceptive simplicity of async and await WIN387 Andrei Marukovich lunarfrog.com @amarukovich
  • 3. • Application errors • Using the UI thread for performing long operations UI unresponsiveness Deceptive simplicity of async and await
  • 4. Deceptive simplicity of async and await Synchronous method private void ButtonClick(object sender, EventArgs e) { WebClient client = new WebClient(); var imageData = client.DownloadData(“http://image-url”); pictureBox.Image = Image.FromStream(new MemoryStream(imageData)); }
  • 5. Deceptive simplicity of async and await Asynchronous method private async void ButtonClick(object sender, EventArgs e) { WebClient client = new WebClient(); var imageData = await client.DownloadDataTaskAsync(“http://image-url”); pictureBox.Image = Image.FromStream(new MemoryStream(imageData)); }
  • 6. Deceptive simplicity of async and await Asynchronous method private async void ButtonClick(object sender, EventArgs e) { WebClient client = new WebClient(); var imageData = await client.DownloadDataTaskAsync(“http://image-url”); pictureBox.Image = Image.FromStream(new MemoryStream(imageData)); var strData = await client.DownloadStringTaskAsync(“http://str-url”); // … }
  • 7. Every API which might take more than 50ms should be async WinRT Deceptive simplicity of async and await
  • 8. Deceptive simplicity of async and await Demo WinRT and async
  • 9. Deep dive Deceptive simplicity of async and await static void Main(string[] args) { DoSomething(); } static void DoSomething() { // method body } static void Main(string[] args) { DoSomething(); } async static Task DoSomething() { // method body }
  • 10. Deep dive Deceptive simplicity of async and await
  • 11. State machine Deceptive simplicity of async and await struct DoSomethingStruct : IAsyncStateMachine { // Argument and local variables public Int32 x; // Compiler-generated variables public Int32 _state; public AsyncTaskMethodBuilder _builder; void MoveNext() { … } }
  • 12. MoveNext() Deceptive simplicity of async and await void MoveNext() { try { switch(_state) { // modified method body } } catch (Exception exception) { _builder.SetException(exception); return; } _builder.SetResult(); }
  • 13. Async function transformation Deceptive simplicity of async and await static Task DoSomething() { var stateMachine = new DoSomethingStruct(); stateMachine._builder = AsyncTaskMethodBuilder.Create(); stateMachine._state = -1; stateMachine._builder.Start(stateMachine); return stateMachine._builder.Task; }
  • 14. Using await Deceptive simplicity of async and await await DoSomething(); Task task = DoSomething(); INotifyCompletion awaiter = task.GetAwaiter(); if (!awaiter.IsCompleted) { awaiter.OnCompleted(continue_delegate) }
  • 15. Bringing it all together async Task Method1() { await Method2(); } async Task Method2() { await _file.CopyAsync(_folder, _name); }
  • 16. Bringing it all together Method1 Method2 Task CopyAsync Copy Task Method2 Method1
  • 17. Defining async methods async Task Method1() { } async Task<StorageFolder> Method2() { return ApplicationData.Current.LocalFolder; } async void button1_Click(object sender, EventArgs e) { }
  • 18. Avoid async void as much as possible Deceptive simplicity of async and await
  • 19. Demo async void and error handling Deceptive simplicity of async and await
  • 20. async lambdas obj.Handle( async () => { await Task.Delay(1000); } ); Deceptive simplicity of async and await void Handle(Func<Task> action); Func<Task> f = async () => { await Task.Delay(1000); } void Handle(Action action); Action a = async () => { await Task.Delay(1000); } IL: AsyncTaskMethodBuilder IL: AsyncVoidMethodBuilder
  • 21. Demo More async in WinRT Deceptive simplicity of async and await
  • 22. Constrains • Cannot use await inside constructor and property accessor • Cannot use await inside catch and finally • Cannot use await inside lock block • Cannot use await inside Main method • An async method cannot have a ref or out parameters
  • 23. What to take away • async/await are not magic • Always await your async operations • async void methods are only suited for UI event handlers • Be careful around async void and exceptions • Be aware of deferral classes in WinRT
  • 24. Next steps • Parallel Programming team blog  http://bit.ly/pfxteam • Deeper into Async and Await, Kathleen Dollard  ARC319 • Three Essential Tips for Async (video)  http://bit.ly/AsyncTips • Async for .NET 4.0 and Windows Phone (NuGet)  http://bit.ly/AsyncNet4