SlideShare a Scribd company logo
1 of 44
Welcome to an
asynchronous world!
Jose Luis Latorre
Geek, MVP, Writer, Speaker
Software engineer – UI Team Lead Developer
Roche Diagnostics
What will we see?
•
•
•
•

Where does Async evolves from?
ABC of Async & Await
Tasks &“The Flow”
How everything gets together in .NET
4.5
• Code!
Asynchronous programming is
becoming the norm in modern,
connected applications
(Anders Hejlsberg)
Synchronous versus
Asynchronous
var data = DownloadData(...);
ProcessData(data);

DownloadDataAsync(... , data =>
{
ProcessData(data);
});
Synchronous versus
Asynchronous
var data = DownloadData(...);
ProcessData(data);

DownloadDataAsync(... , data =>
{
ProcessData(data);
});
Asynchrony is…
about results that are delayed, and yielding
control while awaiting their results (co-operative
multitasking).

Good reasons to use asynchrony:
• for overall control / coordination structure of a
program
• for UI responsiveness
• for IO- and network-bound code
Trends
• Increasingly connected applications
– More latency
– More UI responsiveness problems
– More scalability issues

• Asynchronous programming
– Becoming the norm in responsive, scalable
apps
– Async-only APIs, e.g., Silverlight
A bit of evolution
C# + VB 4.5
Asynchronous
Programming
C# 4.0 + VB 10.0 C# and VB Evolution
Dynamic +
Language Parity
C# 3.0 + VB 9.0
Language Integrated
Query
C# 2.0 + VB 8.0
Generics
C# 1.0 + VB 7.0
Managed Code
A bit of evolution
•
•
•
•

Synchronous programming
APM – Asynchronous Programming Model
EAP – Event Asynchronous Pattern
Async (TAP) – Task Asynchronous Pattern
Synchronous…
Asynchronous with EAP
Asynchronous with Async /
TAP
Look mom, no Callbacks!!
Basics of Async and Await
async
makes your method asynchronous
await
makes the rest of your method a
callback
Task
lets you coordinate activities
Task returning vs void
returning
async Task FooAsync(…);

async void Foo_Click(…);

•
•
•

Can be awaited
“Give back control”
Delegate asynchronous work

•
•
•

Cannot be awaited
“Fire and forget”
Start separate independent flow

•
•

Use for helper methods
Use for library methods

•
•

Use for event handlers
Use to override void methods
DEMO
Using Async & Await
“A waiter’s job is to wait on a table until the patrons have finished their meal.
If you want to serve two tables concurrently, you must hire two waiters.”
Asynchronous Flow
Task<T> combinators

Task
cancel);

Delay(int ms, CancellationToken

Task<T>

Run<T>(Func<T> function);

Task<IEnumerable<T>>

WhenAll<T>(IEnumerable<Task<T>> tasks);

Task<Task<T>>

WhenAny<T>(IEnumerable<Task<T>> tasks);
DEMO
Awaiting Tasks & synchronizing
them
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}
Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}


Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}


Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}




Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}




Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}






Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}








Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}










Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}












Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}














Asynchronous Control Flow
async void DoWorkAsync() {
var t1 = ProcessFeedAsync("www.acme.com/rss");
var t2 = ProcessFeedAsync("www.xyznews.com/rss");
await Task.WhenAll(t1, t2);
DisplayMessage("Done");
}
async Task ProcessFeedAsync(string url) {
var text = await DownloadFeedAsync(url);
var doc = ParseFeedIntoDoc(text);
await SaveDocAsync(doc);
ProcessLog.WriteEntry(url);
}














What have we seen?
•
•
•
•
•

Importance of Asynchronous
Async/Await basics
Tasks
Synchronization
Flow
Comparing TAP to its
predecessors
// Task Asynchronous Pattern [TAP], with Cancellation and Progress
Task<TR> GetStringAsync(Params..., [CancellationToken Cancel],
[IProgress<TP> Progress])

// Asynchronous Programming Model [APM]
IAsyncResult BeginGetString(Params..., AsyncCallback Callback, object state);
TR EndGetString(IAsyncResult);

// Event-based Asynchronous Pattern [EAP]
class C
{
public void GetStringAsync(Params...);
public event GetStringCompletedEventHandler GetStringCompleted;
public void CancelAsync();
}
class GetStringCompletedEventArgs
{
public TR Result { get; }
public Exception Error { get; }
}




Some facts
• Most of the Async methods will complete
Synchronously. They will use a thread only
when really necessary.
• It’s good to minimize the use of Awaits, using
combinators is good (eg, Task.WhenAll).
Jose Luis Latorre
Email: joslat@gmail.com
Twitter: @joslat
Blog: http://xamlguy.com

More Related Content

Viewers also liked

Tiny Review: Constrained by Design
Tiny Review: Constrained by DesignTiny Review: Constrained by Design
Tiny Review: Constrained by DesignMelissa Miranda
 
AR Codes For PokéMon Diamond
AR Codes For PokéMon DiamondAR Codes For PokéMon Diamond
AR Codes For PokéMon Diamondguest9cfd97a
 
Colongate E
Colongate EColongate E
Colongate Ellarboix
 
2009 Employer Partner Info Hmc
2009 Employer Partner Info Hmc2009 Employer Partner Info Hmc
2009 Employer Partner Info HmcLMCaissie
 
Baron Bic Was A Genius
Baron Bic Was A GeniusBaron Bic Was A Genius
Baron Bic Was A GeniusPozzolini
 
Úkrania
ÚkraniaÚkrania
Úkraniajanusg
 
Starten met Infobright
Starten met InfobrightStarten met Infobright
Starten met InfobrightDaan Blinde
 
Emotional design
Emotional designEmotional design
Emotional designKarla Feria
 
Jess & Danny Math Exit Project
Jess & Danny Math Exit ProjectJess & Danny Math Exit Project
Jess & Danny Math Exit ProjectJessicaanddanny
 
Персональные риски аналитика
Персональные риски аналитикаПерсональные риски аналитика
Персональные риски аналитикаGrigoriy Pechenkin
 
Sg Worst Case Debt Scenario
Sg Worst Case Debt ScenarioSg Worst Case Debt Scenario
Sg Worst Case Debt Scenarioinvestoralist
 
iaa 2009 + vicente perez, mikel larios, mikel sanz
iaa 2009 + vicente perez, mikel larios, mikel sanziaa 2009 + vicente perez, mikel larios, mikel sanz
iaa 2009 + vicente perez, mikel larios, mikel sanzvicente46
 
Kumamoto Project
Kumamoto ProjectKumamoto Project
Kumamoto Projectlibera_185
 
Responsible Tourism by Nicolás and Marcos
Responsible Tourism by Nicolás and MarcosResponsible Tourism by Nicolás and Marcos
Responsible Tourism by Nicolás and Marcosvivislide
 
Brovoinet Presentation Eng
Brovoinet Presentation EngBrovoinet Presentation Eng
Brovoinet Presentation EngIvan Warman
 

Viewers also liked (20)

Tiny Review: Constrained by Design
Tiny Review: Constrained by DesignTiny Review: Constrained by Design
Tiny Review: Constrained by Design
 
AR Codes For PokéMon Diamond
AR Codes For PokéMon DiamondAR Codes For PokéMon Diamond
AR Codes For PokéMon Diamond
 
Base New Berlin
Base New BerlinBase New Berlin
Base New Berlin
 
Colongate E
Colongate EColongate E
Colongate E
 
2009 Employer Partner Info Hmc
2009 Employer Partner Info Hmc2009 Employer Partner Info Hmc
2009 Employer Partner Info Hmc
 
Baron Bic Was A Genius
Baron Bic Was A GeniusBaron Bic Was A Genius
Baron Bic Was A Genius
 
Úkrania
ÚkraniaÚkrania
Úkrania
 
Starten met Infobright
Starten met InfobrightStarten met Infobright
Starten met Infobright
 
Emotional design
Emotional designEmotional design
Emotional design
 
Jess & Danny Math Exit Project
Jess & Danny Math Exit ProjectJess & Danny Math Exit Project
Jess & Danny Math Exit Project
 
Персональные риски аналитика
Персональные риски аналитикаПерсональные риски аналитика
Персональные риски аналитика
 
Gallery
GalleryGallery
Gallery
 
Lokacii
LokaciiLokacii
Lokacii
 
Sg Worst Case Debt Scenario
Sg Worst Case Debt ScenarioSg Worst Case Debt Scenario
Sg Worst Case Debt Scenario
 
iaa 2009 + vicente perez, mikel larios, mikel sanz
iaa 2009 + vicente perez, mikel larios, mikel sanziaa 2009 + vicente perez, mikel larios, mikel sanz
iaa 2009 + vicente perez, mikel larios, mikel sanz
 
Kumamoto Project
Kumamoto ProjectKumamoto Project
Kumamoto Project
 
97 03
97 0397 03
97 03
 
Responsible Tourism by Nicolás and Marcos
Responsible Tourism by Nicolás and MarcosResponsible Tourism by Nicolás and Marcos
Responsible Tourism by Nicolás and Marcos
 
Formación sociocultural ii intro
Formación sociocultural ii introFormación sociocultural ii intro
Formación sociocultural ii intro
 
Brovoinet Presentation Eng
Brovoinet Presentation EngBrovoinet Presentation Eng
Brovoinet Presentation Eng
 

Similar to Welcome to an asynchronous world 1.29s

Students to Business Day 2012: Alex Turner
Students to Business Day 2012: Alex TurnerStudents to Business Day 2012: Alex Turner
Students to Business Day 2012: Alex TurnerFrederik De Bruyne
 
C# e Visual Basic Future: Async Made Simple (DEV304)
C# e Visual Basic Future: Async Made Simple (DEV304)C# e Visual Basic Future: Async Made Simple (DEV304)
C# e Visual Basic Future: Async Made Simple (DEV304)Giovanni Bassi
 
C#'ın geleceğine bir bakış webiner
C#'ın geleceğine bir bakış webinerC#'ın geleceğine bir bakış webiner
C#'ın geleceğine bir bakış webinerEnterprisecoding
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍명신 김
 
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
 
Why async matters
Why async mattersWhy async matters
Why async matterstimbc
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextPrateek Maheshwari
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Baruch Sadogursky
 
Airflow tutorials hands_on
Airflow tutorials hands_onAirflow tutorials hands_on
Airflow tutorials hands_onpko89403
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Paco de la Cruz
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service WorkersNAVER D2
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitSpiffy
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 

Similar to Welcome to an asynchronous world 1.29s (20)

C5, vb11, f3
C5, vb11, f3C5, vb11, f3
C5, vb11, f3
 
Students to Business Day 2012: Alex Turner
Students to Business Day 2012: Alex TurnerStudents to Business Day 2012: Alex Turner
Students to Business Day 2012: Alex Turner
 
C# e Visual Basic Future: Async Made Simple (DEV304)
C# e Visual Basic Future: Async Made Simple (DEV304)C# e Visual Basic Future: Async Made Simple (DEV304)
C# e Visual Basic Future: Async Made Simple (DEV304)
 
C#'ın geleceğine bir bakış webiner
C#'ın geleceğine bir bakış webinerC#'ın geleceğine bir bakış webiner
C#'ın geleceğine bir bakış webiner
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
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
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 
Why async matters
Why async mattersWhy async matters
Why async matters
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
 
Airflow tutorials hands_on
Airflow tutorials hands_onAirflow tutorials hands_on
Airflow tutorials hands_on
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service Workers
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 

Recently uploaded

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Welcome to an asynchronous world 1.29s

  • 1. Welcome to an asynchronous world! Jose Luis Latorre Geek, MVP, Writer, Speaker Software engineer – UI Team Lead Developer Roche Diagnostics
  • 2. What will we see? • • • • Where does Async evolves from? ABC of Async & Await Tasks &“The Flow” How everything gets together in .NET 4.5 • Code!
  • 3. Asynchronous programming is becoming the norm in modern, connected applications (Anders Hejlsberg)
  • 4. Synchronous versus Asynchronous var data = DownloadData(...); ProcessData(data); DownloadDataAsync(... , data => { ProcessData(data); });
  • 5. Synchronous versus Asynchronous var data = DownloadData(...); ProcessData(data); DownloadDataAsync(... , data => { ProcessData(data); });
  • 6. Asynchrony is… about results that are delayed, and yielding control while awaiting their results (co-operative multitasking). Good reasons to use asynchrony: • for overall control / coordination structure of a program • for UI responsiveness • for IO- and network-bound code
  • 7. Trends • Increasingly connected applications – More latency – More UI responsiveness problems – More scalability issues • Asynchronous programming – Becoming the norm in responsive, scalable apps – Async-only APIs, e.g., Silverlight
  • 8. A bit of evolution C# + VB 4.5 Asynchronous Programming C# 4.0 + VB 10.0 C# and VB Evolution Dynamic + Language Parity C# 3.0 + VB 9.0 Language Integrated Query C# 2.0 + VB 8.0 Generics C# 1.0 + VB 7.0 Managed Code
  • 9. A bit of evolution • • • • Synchronous programming APM – Asynchronous Programming Model EAP – Event Asynchronous Pattern Async (TAP) – Task Asynchronous Pattern
  • 13. Look mom, no Callbacks!!
  • 14. Basics of Async and Await
  • 15. async makes your method asynchronous
  • 16. await makes the rest of your method a callback
  • 18. Task returning vs void returning async Task FooAsync(…); async void Foo_Click(…); • • • Can be awaited “Give back control” Delegate asynchronous work • • • Cannot be awaited “Fire and forget” Start separate independent flow • • Use for helper methods Use for library methods • • Use for event handlers Use to override void methods
  • 20. “A waiter’s job is to wait on a table until the patrons have finished their meal. If you want to serve two tables concurrently, you must hire two waiters.”
  • 22. Task<T> combinators Task cancel); Delay(int ms, CancellationToken Task<T> Run<T>(Func<T> function); Task<IEnumerable<T>> WhenAll<T>(IEnumerable<Task<T>> tasks); Task<Task<T>> WhenAny<T>(IEnumerable<Task<T>> tasks);
  • 23. DEMO Awaiting Tasks & synchronizing them
  • 24. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 25. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 26. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 27. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 28. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 29. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 30. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 31. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } 
  • 32. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } 
  • 33. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }  
  • 34. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }  
  • 35. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }   
  • 36. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }    
  • 37. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }     
  • 38. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }      
  • 39. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }       
  • 40. Asynchronous Control Flow async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }       
  • 41. What have we seen? • • • • • Importance of Asynchronous Async/Await basics Tasks Synchronization Flow
  • 42. Comparing TAP to its predecessors // Task Asynchronous Pattern [TAP], with Cancellation and Progress Task<TR> GetStringAsync(Params..., [CancellationToken Cancel], [IProgress<TP> Progress]) // Asynchronous Programming Model [APM] IAsyncResult BeginGetString(Params..., AsyncCallback Callback, object state); TR EndGetString(IAsyncResult); // Event-based Asynchronous Pattern [EAP] class C { public void GetStringAsync(Params...); public event GetStringCompletedEventHandler GetStringCompleted; public void CancelAsync(); } class GetStringCompletedEventArgs { public TR Result { get; } public Exception Error { get; } }   
  • 43. Some facts • Most of the Async methods will complete Synchronously. They will use a thread only when really necessary. • It’s good to minimize the use of Awaits, using combinators is good (eg, Task.WhenAll).
  • 44. Jose Luis Latorre Email: joslat@gmail.com Twitter: @joslat Blog: http://xamlguy.com

Editor's Notes

  1. Be water, my friend!Asynchronous operations can share a single thread for multiple control flowsThe UI and IOCP threads are provided by the CLR or OS – reuseCo-Operative multitasking. Wait for tasks to finish and yield control flow while awaiting.
  2. We initially hadvar task2 = task.TimeoutAfter(1000);But we removed it because it didn’t have a clear-enough design. Would you want task2 to end with an OperationCancelledException after 1000ms? Or to end successfully? Both forms are useful. In the end, we figured that cancellation-after-1000ms was easier done like this:var cts = new CancellationTokenSource();cts.CancelAfter(1000)And we figured that successful-termination-after-1000ms was clearer if you wrote it out manually:var task2 = task.WhenAny(task, Task.Delay(1000))