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

PPTX
Introduction to Service Workers | Matteo Manchi
ODP
Building serverless application on the Apache Openwhisk platform
PPTX
Correcting Common Async/Await Mistakes in .NET
PDF
Understanding Asynchronous JavaScript
PPTX
Vs c# lecture11
PDF
The evolution of asynchronous javascript
PDF
Callbacks, promises, generators - asynchronous javascript
PPTX
Understanding reactive programming with microsoft reactive extensions
Introduction to Service Workers | Matteo Manchi
Building serverless application on the Apache Openwhisk platform
Correcting Common Async/Await Mistakes in .NET
Understanding Asynchronous JavaScript
Vs c# lecture11
The evolution of asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
Understanding reactive programming with microsoft reactive extensions

What's hot (20)

PPTX
Avoiding Callback Hell with Async.js
PDF
JavaScript promise
PPTX
Introduction to Jquery
PPTX
Avoiding callback hell in Node js using promises
PPTX
J Query Presentation of David
PPTX
Advanced Jquery
PPTX
Async Programming with C#5: Basics and Pitfalls
PDF
JavaScript Promises
PPTX
PPT
Expert JavaScript tricks of the masters
PPTX
JavaScript Promises
PDF
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
PPTX
Async best practices DotNet Conference 2016
PPTX
Async Best Practices
PDF
Javascript Promises/Q Library
PPTX
Promises, promises, and then observables
PDF
Asynchronous programming done right - Node.js
PDF
NestJS
PDF
Angular and The Case for RxJS
PDF
Using React, Redux and Saga with Lottoland APIs
Avoiding Callback Hell with Async.js
JavaScript promise
Introduction to Jquery
Avoiding callback hell in Node js using promises
J Query Presentation of David
Advanced Jquery
Async Programming with C#5: Basics and Pitfalls
JavaScript Promises
Expert JavaScript tricks of the masters
JavaScript Promises
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Async best practices DotNet Conference 2016
Async Best Practices
Javascript Promises/Q Library
Promises, promises, and then observables
Asynchronous programming done right - Node.js
NestJS
Angular and The Case for RxJS
Using React, Redux and Saga with Lottoland APIs
Ad

Similar to Deceptive simplicity of async and await (20)

PPTX
Windows Phone 8 - 3.5 Async Programming
PPSX
Async-await best practices in 10 minutes
PPSX
What’s New In C# 5.0 - iseltech'13
PPTX
Workshop: Async and Parallel in C#
PDF
Paulo morgado what's new in c# 5.0
PPTX
Async and Await on the Server
PDF
Async Await for Mobile Apps
PPTX
MobConf - session on C# async-await on 18june2016 at Kochi
PPTX
End to-end async and await
PPTX
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
PPTX
Async Programming in C# 5
PDF
Surviving in an Async-First Development World
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
PPTX
C# 5 deep drive into asynchronous programming
PPTX
Training – Going Async
PPTX
What's New In C# 5.0 - Rumos InsideOut
PPTX
C# Async/Await Explained
PDF
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
PPTX
Task parallel library presentation
PDF
Why async matters
Windows Phone 8 - 3.5 Async Programming
Async-await best practices in 10 minutes
What’s New In C# 5.0 - iseltech'13
Workshop: Async and Parallel in C#
Paulo morgado what's new in c# 5.0
Async and Await on the Server
Async Await for Mobile Apps
MobConf - session on C# async-await on 18june2016 at Kochi
End to-end async and await
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Async Programming in C# 5
Surviving in an Async-First Development World
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
C# 5 deep drive into asynchronous programming
Training – Going Async
What's New In C# 5.0 - Rumos InsideOut
C# Async/Await Explained
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
Task parallel library presentation
Why async matters
Ad

More from Andrei Marukovich (8)

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

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Review of recent advances in non-invasive hemoglobin estimation
Machine learning based COVID-19 study performance prediction
Building Integrated photovoltaic BIPV_UPV.pdf
Network Security Unit 5.pdf for BCA BBA.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Unlocking AI with Model Context Protocol (MCP)
sap open course for s4hana steps from ECC to s4
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Chapter 3 Spatial Domain Image Processing.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Approach and Philosophy of On baking technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
Advanced methodologies resolving dimensionality complications for autism neur...
Dropbox Q2 2025 Financial Results & Investor Presentation
“AI and Expert System Decision Support & Business Intelligence Systems”
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
Review of recent advances in non-invasive hemoglobin estimation

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