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

Colongate E
Colongate EColongate E
Colongate E
llarboix
 
2009 Employer Partner Info Hmc
2009 Employer Partner Info Hmc2009 Employer Partner Info Hmc
2009 Employer Partner Info Hmc
LMCaissie
 
Emotional design
Emotional designEmotional design
Emotional design
Karla Feria
 
Jess & Danny Math Exit Project
Jess & Danny Math Exit ProjectJess & Danny Math Exit Project
Jess & Danny Math Exit Project
Jessicaanddanny
 
Sg Worst Case Debt Scenario
Sg Worst Case Debt ScenarioSg Worst Case Debt Scenario
Sg Worst Case Debt Scenario
investoralist
 
Kumamoto Project
Kumamoto ProjectKumamoto Project
Kumamoto Project
libera_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 Marcos
vivislide
 

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 Turner
Frederik De Bruyne
 
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
Oliver Scheer
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
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
Spiffy
 

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

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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))