SlideShare uma empresa Scribd logo
1 de 24
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

Mais conteúdo relacionado

Mais procurados

Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsEastBanc Tachnologies
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript PromisesTomasz Bak
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerIslam Sharabash
 
Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016 Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016 Lluis Franco
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best PracticesLluis Franco
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsMihail Gaberov
 

Mais procurados (20)

Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to Jquery
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
J Query Presentation of David
J Query Presentation of DavidJ Query Presentation of David
J Query Presentation of David
 
Advanced Jquery
Advanced JqueryAdvanced Jquery
Advanced Jquery
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and Pitfalls
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Workers
WorkersWorkers
Workers
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
 
Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016 Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
NestJS
NestJSNestJS
NestJS
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 

Semelhante a Deceptive simplicity of async and await in .NET

Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questionsarchana singh
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...GeeksLab Odessa
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadWASdev Community
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Codemotion
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonLuciano Mammino
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événementsJean Michel
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns Luciano Mammino
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Christophe Spring Actionscript Flex Java Exchange
Christophe Spring Actionscript Flex Java ExchangeChristophe Spring Actionscript Flex Java Exchange
Christophe Spring Actionscript Flex Java ExchangeSkills Matter
 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina Belgium
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 

Semelhante a Deceptive simplicity of async and await in .NET (20)

Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questions
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Christophe Spring Actionscript Flex Java Exchange
Christophe Spring Actionscript Flex Java ExchangeChristophe Spring Actionscript Flex Java Exchange
Christophe Spring Actionscript Flex Java Exchange
 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTP
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 

Mais de Andrei Marukovich

Using NuGet libraries in your application
Using NuGet libraries in your applicationUsing NuGet libraries in your application
Using NuGet libraries in your applicationAndrei Marukovich
 
C# code sharing across the platforms
C# code sharing across the platformsC# code sharing across the platforms
C# code sharing across the platformsAndrei Marukovich
 
Open Source Libraries for.NET developers
Open Source Libraries for.NET developersOpen Source Libraries for.NET developers
Open Source Libraries for.NET developersAndrei Marukovich
 
Reactive Extensions for .NET
Reactive Extensions for .NETReactive Extensions for .NET
Reactive Extensions for .NETAndrei Marukovich
 
All about data persistence in Windows 8
All about data persistence in Windows 8All about data persistence in Windows 8
All about data persistence in Windows 8Andrei Marukovich
 
A Developer's View of Windows 8
A Developer's View of Windows 8A Developer's View of Windows 8
A Developer's View of Windows 8Andrei Marukovich
 

Mais de Andrei Marukovich (8)

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

Último

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 

Último (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 

Deceptive simplicity of async and await in .NET

  • 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