SlideShare a Scribd company logo
1 of 28
Async Programming with C# 5:
Basics and Pitfalls
Async Await Basics
public static async Task ReadAsync(string path1, string path2)
{
using (FileStream fs1 = new FileStream(path1, FileMode.Open))
using (FileStream fs2 = new FileStream(path2, FileMode.Open))
{
await fs1.ReadAsync(new byte[1], 0, 1);
await fs2.ReadAsync(new byte[1], 0, 1);
}
}
Async Await Basics
public static IEnumerable<string> GetStringList()
{
yield return "1";
yield return "2";
}
Async control flow
public static async Task<string> GetAsync()
{
var client = new HttpClient();
var response = await client.GetAsync("http://google.com"); // 1
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadAsStringAsync(); // 2
}
What is the difference between the two?
public static async Task<HttpResponseMessage> ReadAsync() {
var client = new HttpClient();
return await client.GetAsync("http://google.com");
}
public static Task<HttpResponseMessage> ReadAsync() {
var client = new HttpClient();
return client.GetAsync("http://google.com");
}
What is the difference between the two?
public static async Task<HttpResponseMessage> ReadAsync() {
var client = new HttpClient();
throw new Exception();
return await client.GetAsync("http://google.com");
}
public static Task<HttpResponseMessage> ReadAsync() {
var client = new HttpClient();
throw new Exception();
return client.GetAsync("http://google.com");
}
private static void MainMethod() {
Task<HttpResponseMessage> task = ReadAsync();
HttpResponseMessage message = task.Result;
}
What will happen to the exception?
private static void MainMethod() {
try {
ReadAsync();
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
public static async Task ReadAsync() {
var client = new HttpClient();
var message = await client.GetAsync("http://google.com");
throw new Exception();
}
.Wait()
Key Points
• Exceptions generated inside a state machine don’t behave the same way
as exceptions in sync methods
What will happen to the exception?
private static void MainMethod() {
try {
ReadAsync();
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
public static async void ReadAsync() {
var client = new HttpClient();
var message = await client.GetAsync("http://google.com");
throw new Exception();
}
Key Points
• Exceptions generated inside a state machine don’t behave the same
ways as usual exceptions
• Exceptions in async void methods are dispatched directly to the UI
thread
Key Points
• Exceptions generated inside a state machine don’t behave the same
ways as usual exceptions
• Exceptions in async void methods are dispatched directly to the UI
thread
• Don’t use async void methods anywhere except top-level event handlers
No need to sync access to UI elements
private async void btnRead_Click(object sender, EventArgs e)
{
btnRead.Enabled = false;
using (var fs = new FileStream("1.txt", FileMode.Open))
using (var sr = new StreamReader(fs))
{
Content = await sr.ReadToEndAsync();
}
btnRead.Enabled = true;
}
Before the Async await feature
if (btnRead.InvokeRequired)
{
btnRead.Invoke((Action)(() => btnRead.Enabled = false));
}
else
{
btnRead.Enabled = false;
}
No need to sync access to UI elements
private async void btnRead_Click(object sender, EventArgs e)
{
btnRead.Enabled = false;
using (var fs = new FileStream("1.txt", FileMode.Open))
using (var sr = new StreamReader(fs))
{
Content = await sr.ReadToEndAsync()
}
btnRead.Enabled = true;
}
.ConfigureAwait(true);
DEadlock
private async void button1_Click(object sender, EventArgs e)
{
int result = DoSomeWorkAsync().Result; // 1
}
private async Task<int> DoSomeWorkAsync()
{
await Task.Delay(100).ConfigureAwait(true); // 2
return 1;
}
DEadlock
private async void button1_Click(object sender, EventArgs e)
{
int result = DoSomeWorkAsync().Result; // 1
}
private async Task<int> DoSomeWorkAsync()
{
await Task.Delay(100).ConfigureAwait(true); // 2
return 1;
}
await
DEadlock
private async void button1_Click(object sender, EventArgs e)
{
int result = DoSomeWorkAsync().Result; // 1
}
private async Task<int> DoSomeWorkAsync()
{
await Task.Delay(100).ConfigureAwait(true); // 2
return 1;
}
await
false
Key Points
• Exceptions generated inside a state machine don’t behave the same
ways as usual exceptions
• Exceptions in async void methods are dispatched directly to the UI
thread
• Don’t use async void methods anywhere except top-level event handlers
• When building a 3rd party library, always put ConfigureAwait(false) in
your async methods
CPU-bound vs IO-bound work
• CPU-bound work: some calculations; work performed by the CPU
• IO-bound work: work performed by external, non-CPU devices
CPU-bound vs IO-bound work
private async void button1_Click(object sender, EventArgs e)
{
btnCalculate.Enabled = false;
double pi = await Task.Run(() => CalculatePi()); // CPU-bound work
btnCalculate.Enabled = true;
}
public async void button1_Click(object sender, EventArgs e)
{
btnLoad.Enabled = false;
var client = new HttpClient();
var page = await client.GetAsync("http://google.com"); // IO-bound work
btnLoad.Enabled = true;
}
Key Points
• Exceptions generated inside a state machine don’t behave the same
ways as usual exceptions
• Exceptions in async void methods are dispatched directly to the UI
thread
• Don’t use async void methods anywhere except top-level event handlers
• When building a 3rd party library, always put ConfigureAwait(false) in
your async methods
• Don’t conflate IO-bound and CPU-bound work
Don’t conflate IO-bound and CPU-bound work
private Task<string> ReadFileAsync()
{
return Task.Run(() => // 1
{
using (var fs = new FileStream("1.txt", FileMode.Open))
using (var sr = new StreamReader(fs))
{
return sr.ReadToEnd(); // 2
}
});
}
Don’t conflate IO-bound and CPU-bound work
private async Task<string> ReadFileAsync()
{
using (var fs = new FileStream("1.txt", FileMode.Open))
using (var sr = new StreamReader(fs))
{
return await sr.ReadToEndAsync();
}
}
Key Points
• Exceptions generated inside a state machine don’t behave the same
ways as usual exceptions
• Exceptions in async void methods are dispatched directly to the UI
thread
• Don’t use async void methods anywhere except top-level event handlers
• When building a 3rd party library, always put ConfigureAwait(false) in
your async methods
• Don’t conflate IO-bound and CPU-bound work
Q&A
27
THANK YOU
Vladimir Khorikov
Developer
vkhorikov@eastbanctech.com
eastbanctech.com

More Related Content

What's hot

Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelinescpsitgmbh
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptLeonardo Borges
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptLeonardo Borges
 
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
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_iNico Ludwig
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftAaron Douglas
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programmingEric Polerecky
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript PromisesTomasz Bak
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
Day3_Part 1_Apache_JMeter_Logic_Controllers
Day3_Part 1_Apache_JMeter_Logic_ControllersDay3_Part 1_Apache_JMeter_Logic_Controllers
Day3_Part 1_Apache_JMeter_Logic_ControllersSravanthi N
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronouskang taehun
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 

What's hot (20)

Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
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
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
Day3_Part 1_Apache_JMeter_Logic_Controllers
Day3_Part 1_Apache_JMeter_Logic_ControllersDay3_Part 1_Apache_JMeter_Logic_Controllers
Day3_Part 1_Apache_JMeter_Logic_Controllers
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronous
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
New text document
New text documentNew text document
New text document
 

Viewers also liked

Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
No More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETNo More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETFilip Ekberg
 
Proyecto etwinning: ¿qué nos hace seres humanos?
Proyecto etwinning: ¿qué nos hace seres humanos?Proyecto etwinning: ¿qué nos hace seres humanos?
Proyecto etwinning: ¿qué nos hace seres humanos?Mariely Zarraga Landa
 
Hip and spine syndrome (PMR)
Hip and spine syndrome (PMR)Hip and spine syndrome (PMR)
Hip and spine syndrome (PMR)mrinal joshi
 
Tips for setting up Salesforce1 mobile apps
Tips for setting up Salesforce1 mobile appsTips for setting up Salesforce1 mobile apps
Tips for setting up Salesforce1 mobile appsAvi Verma
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programmingFilip Ekberg
 
RONALD L'ETOILE Resume Current
RONALD L'ETOILE Resume CurrentRONALD L'ETOILE Resume Current
RONALD L'ETOILE Resume CurrentRonald LEtoile
 
Expedient edivorcio por causal de atentado a la vida
Expedient edivorcio por causal de atentado a la vidaExpedient edivorcio por causal de atentado a la vida
Expedient edivorcio por causal de atentado a la vidajose rojas
 

Viewers also liked (16)

Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
No More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETNo More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NET
 
Proyecto etwinning: ¿qué nos hace seres humanos?
Proyecto etwinning: ¿qué nos hace seres humanos?Proyecto etwinning: ¿qué nos hace seres humanos?
Proyecto etwinning: ¿qué nos hace seres humanos?
 
Men collection
Men collectionMen collection
Men collection
 
Happy New Year &amp; Gmar Hatima Tova
Happy New Year &amp; Gmar Hatima TovaHappy New Year &amp; Gmar Hatima Tova
Happy New Year &amp; Gmar Hatima Tova
 
Rutina 3,2,1 grupo a
Rutina 3,2,1  grupo aRutina 3,2,1  grupo a
Rutina 3,2,1 grupo a
 
Rutina 3,2,1 grupo b (1)
Rutina 3,2,1  grupo b (1)Rutina 3,2,1  grupo b (1)
Rutina 3,2,1 grupo b (1)
 
Hip and spine syndrome (PMR)
Hip and spine syndrome (PMR)Hip and spine syndrome (PMR)
Hip and spine syndrome (PMR)
 
Tips for setting up Salesforce1 mobile apps
Tips for setting up Salesforce1 mobile appsTips for setting up Salesforce1 mobile apps
Tips for setting up Salesforce1 mobile apps
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Jewellery planet!
Jewellery planet!Jewellery planet!
Jewellery planet!
 
DIABETES_E-Packet-2
DIABETES_E-Packet-2DIABETES_E-Packet-2
DIABETES_E-Packet-2
 
RONALD L'ETOILE Resume Current
RONALD L'ETOILE Resume CurrentRONALD L'ETOILE Resume Current
RONALD L'ETOILE Resume Current
 
Expedient edivorcio por causal de atentado a la vida
Expedient edivorcio por causal de atentado a la vidaExpedient edivorcio por causal de atentado a la vida
Expedient edivorcio por causal de atentado a la vida
 
Jumper changing to back
Jumper changing to backJumper changing to back
Jumper changing to back
 

Similar to Async Programming with C#5: Basics and Pitfalls

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Deceptive simplicity of async and await
Deceptive simplicity of async and awaitDeceptive simplicity of async and await
Deceptive simplicity of async and awaitAndrei Marukovich
 
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
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best PracticesLluis Franco
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍명신 김
 
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Lifeparticle
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
State management in asp
State management in aspState management in asp
State management in aspIbrahim MH
 
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
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Top 3 SWT Exceptions
Top 3 SWT ExceptionsTop 3 SWT Exceptions
Top 3 SWT ExceptionsLakshmi Priya
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
cse581_03_EventProgramming.ppt
cse581_03_EventProgramming.pptcse581_03_EventProgramming.ppt
cse581_03_EventProgramming.ppttadudemise
 

Similar to Async Programming with C#5: Basics and Pitfalls (20)

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Deceptive simplicity of async and await
Deceptive simplicity of async and awaitDeceptive simplicity of async and await
Deceptive simplicity of async and await
 
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...
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
2310 b 05
2310 b 052310 b 05
2310 b 05
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
Advanced Jquery
Advanced JqueryAdvanced Jquery
Advanced Jquery
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 
Welcome to an asynchronous world 1.29s
Welcome to an asynchronous world 1.29sWelcome to an asynchronous world 1.29s
Welcome to an asynchronous world 1.29s
 
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
State management in asp
State management in aspState management in asp
State management in asp
 
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
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Day 5
Day 5Day 5
Day 5
 
Top 3 SWT Exceptions
Top 3 SWT ExceptionsTop 3 SWT Exceptions
Top 3 SWT Exceptions
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
cse581_03_EventProgramming.ppt
cse581_03_EventProgramming.pptcse581_03_EventProgramming.ppt
cse581_03_EventProgramming.ppt
 

More from EastBanc Tachnologies

Unpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesUnpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesEastBanc Tachnologies
 
Azure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectAzure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectEastBanc Tachnologies
 
Getting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesGetting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesEastBanc Tachnologies
 
Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0EastBanc Tachnologies
 
Highlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceHighlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceEastBanc Tachnologies
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
EastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Tachnologies
 
EastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Tachnologies
 
EastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Tachnologies
 
EastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Tachnologies
 
Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#EastBanc Tachnologies
 

More from EastBanc Tachnologies (14)

Unpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesUnpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc Technologies
 
Azure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectAzure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your project
 
Functional Programming with C#
Functional Programming with C#Functional Programming with C#
Functional Programming with C#
 
Getting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesGetting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics services
 
DevOps with Kubernetes
DevOps with KubernetesDevOps with Kubernetes
DevOps with Kubernetes
 
Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0
 
Highlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceHighlights from MS build\\2016 Conference
Highlights from MS build\\2016 Conference
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Estimating for Fixed Price Projects
Estimating for Fixed Price ProjectsEstimating for Fixed Price Projects
Estimating for Fixed Price Projects
 
EastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and Innovation
 
EastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint Portfolio
 
EastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI Portfolio
 
EastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS Portfolio
 
Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#
 

Recently uploaded

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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
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
 

Recently uploaded (20)

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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 
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
 
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
 

Async Programming with C#5: Basics and Pitfalls

  • 1. Async Programming with C# 5: Basics and Pitfalls
  • 2. Async Await Basics public static async Task ReadAsync(string path1, string path2) { using (FileStream fs1 = new FileStream(path1, FileMode.Open)) using (FileStream fs2 = new FileStream(path2, FileMode.Open)) { await fs1.ReadAsync(new byte[1], 0, 1); await fs2.ReadAsync(new byte[1], 0, 1); } }
  • 3.
  • 4. Async Await Basics public static IEnumerable<string> GetStringList() { yield return "1"; yield return "2"; }
  • 5.
  • 6. Async control flow public static async Task<string> GetAsync() { var client = new HttpClient(); var response = await client.GetAsync("http://google.com"); // 1 if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadAsStringAsync(); // 2 }
  • 7. What is the difference between the two? public static async Task<HttpResponseMessage> ReadAsync() { var client = new HttpClient(); return await client.GetAsync("http://google.com"); } public static Task<HttpResponseMessage> ReadAsync() { var client = new HttpClient(); return client.GetAsync("http://google.com"); }
  • 8. What is the difference between the two? public static async Task<HttpResponseMessage> ReadAsync() { var client = new HttpClient(); throw new Exception(); return await client.GetAsync("http://google.com"); } public static Task<HttpResponseMessage> ReadAsync() { var client = new HttpClient(); throw new Exception(); return client.GetAsync("http://google.com"); } private static void MainMethod() { Task<HttpResponseMessage> task = ReadAsync(); HttpResponseMessage message = task.Result; }
  • 9. What will happen to the exception? private static void MainMethod() { try { ReadAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static async Task ReadAsync() { var client = new HttpClient(); var message = await client.GetAsync("http://google.com"); throw new Exception(); } .Wait()
  • 10. Key Points • Exceptions generated inside a state machine don’t behave the same way as exceptions in sync methods
  • 11. What will happen to the exception? private static void MainMethod() { try { ReadAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static async void ReadAsync() { var client = new HttpClient(); var message = await client.GetAsync("http://google.com"); throw new Exception(); }
  • 12. Key Points • Exceptions generated inside a state machine don’t behave the same ways as usual exceptions • Exceptions in async void methods are dispatched directly to the UI thread
  • 13. Key Points • Exceptions generated inside a state machine don’t behave the same ways as usual exceptions • Exceptions in async void methods are dispatched directly to the UI thread • Don’t use async void methods anywhere except top-level event handlers
  • 14. No need to sync access to UI elements private async void btnRead_Click(object sender, EventArgs e) { btnRead.Enabled = false; using (var fs = new FileStream("1.txt", FileMode.Open)) using (var sr = new StreamReader(fs)) { Content = await sr.ReadToEndAsync(); } btnRead.Enabled = true; }
  • 15. Before the Async await feature if (btnRead.InvokeRequired) { btnRead.Invoke((Action)(() => btnRead.Enabled = false)); } else { btnRead.Enabled = false; }
  • 16. No need to sync access to UI elements private async void btnRead_Click(object sender, EventArgs e) { btnRead.Enabled = false; using (var fs = new FileStream("1.txt", FileMode.Open)) using (var sr = new StreamReader(fs)) { Content = await sr.ReadToEndAsync() } btnRead.Enabled = true; } .ConfigureAwait(true);
  • 17. DEadlock private async void button1_Click(object sender, EventArgs e) { int result = DoSomeWorkAsync().Result; // 1 } private async Task<int> DoSomeWorkAsync() { await Task.Delay(100).ConfigureAwait(true); // 2 return 1; }
  • 18. DEadlock private async void button1_Click(object sender, EventArgs e) { int result = DoSomeWorkAsync().Result; // 1 } private async Task<int> DoSomeWorkAsync() { await Task.Delay(100).ConfigureAwait(true); // 2 return 1; } await
  • 19. DEadlock private async void button1_Click(object sender, EventArgs e) { int result = DoSomeWorkAsync().Result; // 1 } private async Task<int> DoSomeWorkAsync() { await Task.Delay(100).ConfigureAwait(true); // 2 return 1; } await false
  • 20. Key Points • Exceptions generated inside a state machine don’t behave the same ways as usual exceptions • Exceptions in async void methods are dispatched directly to the UI thread • Don’t use async void methods anywhere except top-level event handlers • When building a 3rd party library, always put ConfigureAwait(false) in your async methods
  • 21. CPU-bound vs IO-bound work • CPU-bound work: some calculations; work performed by the CPU • IO-bound work: work performed by external, non-CPU devices
  • 22. CPU-bound vs IO-bound work private async void button1_Click(object sender, EventArgs e) { btnCalculate.Enabled = false; double pi = await Task.Run(() => CalculatePi()); // CPU-bound work btnCalculate.Enabled = true; } public async void button1_Click(object sender, EventArgs e) { btnLoad.Enabled = false; var client = new HttpClient(); var page = await client.GetAsync("http://google.com"); // IO-bound work btnLoad.Enabled = true; }
  • 23. Key Points • Exceptions generated inside a state machine don’t behave the same ways as usual exceptions • Exceptions in async void methods are dispatched directly to the UI thread • Don’t use async void methods anywhere except top-level event handlers • When building a 3rd party library, always put ConfigureAwait(false) in your async methods • Don’t conflate IO-bound and CPU-bound work
  • 24. Don’t conflate IO-bound and CPU-bound work private Task<string> ReadFileAsync() { return Task.Run(() => // 1 { using (var fs = new FileStream("1.txt", FileMode.Open)) using (var sr = new StreamReader(fs)) { return sr.ReadToEnd(); // 2 } }); }
  • 25. Don’t conflate IO-bound and CPU-bound work private async Task<string> ReadFileAsync() { using (var fs = new FileStream("1.txt", FileMode.Open)) using (var sr = new StreamReader(fs)) { return await sr.ReadToEndAsync(); } }
  • 26. Key Points • Exceptions generated inside a state machine don’t behave the same ways as usual exceptions • Exceptions in async void methods are dispatched directly to the UI thread • Don’t use async void methods anywhere except top-level event handlers • When building a 3rd party library, always put ConfigureAwait(false) in your async methods • Don’t conflate IO-bound and CPU-bound work