SlideShare a Scribd company logo
Marek Safar
Engineer
Xamarin
msafar@xamarin.com
Using Async in Your Apps
You?
Wikipedia
“Asynchronous events are those occurring independently
of the main program flow. Asynchronous actions are
actions executed in a non-blocking scheme, allowing the
main program flow to continue processing”
You Should Use Async Today
• Your UI always remains responsive
• No need to guard against race conditions
• No ugly callbacks
• Compiler does all the heavy li!ing
Using Async in your Mobile Apps - Marek Safar
Async in C#
• New major feature of C# 5.0
Makes asynchronous programming a first-class citizen in C#
Important part of C# – as significant as LINQ
• New async modifier keyword introduced
• Methods, lambda expressions, and anonymous methods can be
asynchronous
• New contextual keyword await introduced
Adding Async to Your Codebase
• Decorated with new async modifier
• Async method must return one of
Task, Task<T> or void type
• Async anonymous method and lambdas
Delegates returning Task, Task<T> or void
• Very few restrictions
No ref or out parameters allowed
No unsafe code
No Main async method
No async iterators (aka IAsyncEnumerable<T>)
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Example: Calculating a Price Asynchronously
public	
  async	
  Task<int>	
  CalculatePriceAsync	
  (Item[]	
  items)
{
int	
  price;
//	
  Calculate	
  price	
  asynchronously	
  and	
  return	
  the	
  value
return	
  price;
}
public	
  override	
  void	
  ViewDidLoad	
  ()
{
button.TouchDown	
  +=	
  async	
  (sender,	
  e)	
  =>	
  {
//	
  This	
  is	
  asynchronous	
  handler
};
}
Await Introduction
• Await can be used in async context only
Marks a suspension point
Can be used anywhere (except catch and finally blocks)
Requires awaitable types (Task, Task<T> but can be any
custom type)
As many as you like inside async block
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Calculating a Price Asynchronously
public	
  async	
  Task<int>	
  CalculatePriceAsync	
  (Item[]	
  items)
{
using	
  (var	
  cmd	
  =	
  CreateSqlCommand	
  (Calculations.TotalPrice,	
  items))	
  {
using	
  (var	
  reader	
  =	
  await	
  cmd.ExecuteReaderAsync	
  ())	
  {
int	
  price	
  =	
  ReadPrice	
  (reader);
return	
  price;
}
}
}
public	
  override	
  void	
  ViewDidLoad	
  ()
{
button.TouchDown	
  +=	
  async	
  (sender,	
  e)	
  =>	
  {
var	
  price	
  =	
  await	
  CalculatePriceAsync	
  (items);
priceLabel.Text	
  =	
  price.ToString	
  ();
};
}
Cancelling an Async Task
• CancellationToken controls cancellation process
• Async method needs explicitly support it
Usually another method overload
Task SaveAsync (CancellationToken token)
• Caller calls Cancel on CancellationTokenSource
Async method stops and returns Task with cancelled state
Implementation detail how quickly async method terminates
DEMO
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Async Language Features
public	
  async	
  Task	
  RealAsync	
  ()
{
//	
  This	
  is	
  real	
  async	
  heavy	
  code	
  (only	
  7	
  awaits	
  someone	
  else	
  will
//	
  certainly	
  do	
  better)
var	
  test	
  =	
  new	
  TestClass	
  (await	
  CallAsync	
  ()	
  |	
  await	
  CallAsync	
  ())	
  {
	
   Latitude	
  =	
  await	
  GetLatitudeAsync	
  (await	
  AnotherAsync	
  ()),
	
   Roles	
  =	
  from	
  role	
  in	
  await	
  GetRolesAsync	
  ()
	
  where	
  role	
  ==	
  "agent"	
  select	
  role
};
....
test	
  [await	
  CallAsync	
  ()]	
  =	
  new	
  int[]	
  {	
  33,	
  await	
  GetIntAsync	
  ()	
  };
...
}
Best Practices
• Use Async naming suffix for asynchronous methods
LoadAsync, SendAsync, etc.
Only recommended naming convention
• Return Task or Task<T> preferably
Task for SaveAsync like methods
Task<T> for ReadAsync like methods
Leave async void to event handlers only
• Support cancellation, if possible
Synchronization Context
• Framework abstraction over UI toolkit threading model
NSRunLoop, DispatchContext in Xamarin.iOS
MainLooper in Xamarin.Android
Dispatcher in WPF
etc.
• Await uses synchronization context to restore back suspended
context
SynchronizationContext::Post method is used
Suspension on UI thread resumes back on same UI thread as
“expected”
Sometimes Things Go Wrong
• Async returning Task or Task<T>
Task state is set to Faulted
Exception is re-thrown when Task is checked (awaited)
• Async void
Fire and forget asynchrony
Exception is thrown on current synchronization context and your
app will crash
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Exception Handling with Await
public	
  override	
  void	
  ViewDidLoad	
  ()
{
button.TouchDown	
  +=	
  async	
  (sender,	
  e)	
  =>	
  {
try	
  {
button.Enabled	
  =	
  false;
var	
  price	
  =	
  await	
  CalculatePriceAsync	
  (items);
priceLabel.Text	
  =	
  price.ToString	
  ();
}	
  catch	
  (Exception	
  ex)	
  {
//	
  Handles	
  price	
  calculation	
  error
priceLabel.Text	
  =	
  "Calculation	
  failed";
Debug.Print	
  (ex.ToString	
  ());	
  //	
  Simple	
  exception	
  logging
}	
  finally	
  {
button.Enabled	
  =	
  true;
}
};
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Exception Throwing
public	
  async	
  Task<int>	
  CalculatePriceAsync	
  (Item[]	
  items)
{
if	
  (items	
  ==	
  null)	
  {
//	
  Throw	
  before	
  suspension
throw	
  new	
  ArgumentNullException	
  ("items");
}
...
var	
  price	
  =	
  await	
  CalculatePriceAsync	
  (items);
if	
  (price	
  <	
  0)	
  {
//	
  Throw	
  after	
  suspension
throw	
  new	
  ArgumentException	
  ("Invalid	
  items");
}
...
}
Diving Deeper
• Await can work with any type which implements the awaiter
pattern
• Task and Task<T> types do since .NET 4.5
• Any custom type can be made awaitable
Has an accessible method called GetAwaiter returning a type which
Implements the interface INotifyCompletion
Has property IsCompleted of type bool
Has method GetResult with no parameters
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Custom await Behaviour
public	
  async	
  Task<int>	
  SomeAsync	
  ()
{
	
  	
  ...
	
  	
  await	
  3000;	
  //	
  This	
  does	
  not	
  compile	
  unless	
  we	
  provide	
  custom	
  awaiter
	
  	
  ...
}
//	
  Name	
  of	
  the	
  method	
  is	
  important
static	
  TaskAwaiter	
  GetAwaiter	
  (this	
  int	
  millisecondsDelay)
{
	
  	
  return	
  Task.Delay	
  (millisecondsDelay).GetAwaiter	
  ();
}
Async Deadlocks
• await restores execution context based on current
SynchronizationContext
Good for most application code
Bad for most library code
• Don’t block the UI thread
Good old rule still applies in async world
Use await when possible
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Async Deadlock Example
public	
  async	
  Task<int>	
  CalculatePriceAsync	
  (Item[]	
  items)
{
using	
  (var	
  cmd	
  =	
  CreateSqlCommand	
  (Calculations.TotalPrice,	
  items))	
  {
using	
  (var	
  r	
  =	
  await	
  cmd.ExecuteReaderAsync	
  ())	
  {
.....
}
}
}
//	
  The	
  method	
  itself	
  cannot	
  be	
  async
public	
  override	
  bool	
  FinishedLaunching	
  (UIApplication	
  app,	
  NSDictionary	
  options)
{
....
int	
  price	
  =	
  CalculatePriceAsync	
  (items).Result;	
  	
  //	
  Synchronous	
  wait
//	
  This	
  line	
  won’t	
  be	
  reached	
  if	
  flow	
  suspension	
  occurred
}
Controlling the Synchronization Context
• ConfigureAwait (bool)
Controls captured context behaviour
• true value - default behaviour
Continue execution on context async was called from
Important for UI to switch back to UI context
• false value
Avoids expensive context switching
Avoids possible deadlocks on blocking UI
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Async Deadlock Fixed
public	
  async	
  Task<int>	
  CalculatePriceAsync	
  (Item[]	
  items)
{
using	
  (var	
  cmd	
  =	
  CreateSqlCommand	
  (Calculations.TotalPrice,	
  items))	
  {
using	
  (var	
  r	
  =	
  await	
  cmd.ExecuteReaderAsync	
  ().ConfigureAwait	
  (false))	
  {
//	
  The	
  context	
  is	
  not	
  restored	
  but	
  that’s	
  fine	
  for	
  no	
  UI	
  method	
  
}
}
}
//	
  The	
  method	
  itself	
  cannot	
  be	
  async
public	
  override	
  bool	
  FinishedLaunching	
  (UIApplication	
  app,	
  NSDictionary	
  options)
{
....
int	
  price	
  =	
  CalculatePriceAsync	
  (items).Result;	
  	
  //	
  Synchronous	
  wait
//	
  Program	
  continues	
  when	
  the	
  wait	
  is	
  signalled
}
Combinators
• Asynchronously wait on multiple asynchronous operations
Better than individual awaits of multiple tasks
The result can be awaited (Task of Tasks)
• Task.WhenAll (IEnumerable<Task>)
Completes when all of the individual tasks have completed
• Task.WhenAny (IEnumerable<Task>)
Completes when any of the individual tasks have completed
The Compiler Magic
• Compiler does all the “magic”
• Local variable and parameters are li!ed into compiler generated
type
Compiler converts variables and parameters to fields
• Any stack values need to be li!ed too
Stack needs to be restored a"er suspension
• Try-Catch block over any async block
• No suspension when awaited task finished
Best Practices - Performance
• Use ConfigureAwait when you can
• Reduce number of local variables
Move async block into separate method or lambda expression
Pass variables as parameters
Avoid deep await usage
• Cache Task not task result
• Don’t over use async
Use async only when appropriate (unreliable tasks, running >50ms)
Async has its own overhead
Get Your Hands on Async
• Async is available today
Xamarin.iOS Beta release
Xamarin.Android Beta release
Xamarin Studio async support
• Give us feedback on our new async API
Forums
Bugzilla
Mailing list
IRC
Q&A
THANK YOU

More Related Content

PDF
Async Await for Mobile Apps
PPTX
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
PPTX
C# 5 deep drive into asynchronous programming
PPTX
Async in .NET
PPSX
Async-await best practices in 10 minutes
PPTX
End to-end async and await
PPT
Asynchronous Programming in C# - Part 1
PPTX
Async Programming in C# 5
Async Await for Mobile Apps
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# 5 deep drive into asynchronous programming
Async in .NET
Async-await best practices in 10 minutes
End to-end async and await
Asynchronous Programming in C# - Part 1
Async Programming in C# 5

What's hot (20)

PPTX
Async and Await on the Server
PPTX
CTU June 2011 - C# 5.0 - ASYNC & Await
PPTX
Task parallel library presentation
PPTX
Async CTP 3 Presentation for MUGH 2012
PPTX
Asynchronous Programming in ASP.NET
PDF
Anatomy of a Reactive Application
PPTX
CSharp 5 Async
PDF
Javascript internals
PDF
Variables in Pharo5
PDF
Dynamically Composing Collection Operations through Collection Promises
PDF
Reflection in Pharo: Beyond Smalltak
PDF
Reflection in Pharo: Beyond Smalltak
PDF
Using assm in service object
PPTX
Continuous deployment of Rails apps on AWS OpsWorks
PDF
Async/Await: TPL & Message Pumps
PDF
Gatling @ Scala.Io 2013
PDF
Reflection in Pharo5
PDF
DRAKON Visual Language: Tutorial. Part 2
PDF
Async/Await Best Practices
PDF
Reactive programming with Rxjava
Async and Await on the Server
CTU June 2011 - C# 5.0 - ASYNC & Await
Task parallel library presentation
Async CTP 3 Presentation for MUGH 2012
Asynchronous Programming in ASP.NET
Anatomy of a Reactive Application
CSharp 5 Async
Javascript internals
Variables in Pharo5
Dynamically Composing Collection Operations through Collection Promises
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
Using assm in service object
Continuous deployment of Rails apps on AWS OpsWorks
Async/Await: TPL & Message Pumps
Gatling @ Scala.Io 2013
Reflection in Pharo5
DRAKON Visual Language: Tutorial. Part 2
Async/Await Best Practices
Reactive programming with Rxjava
Ad

Viewers also liked (18)

PPT
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
PPTX
Asynchronous programming from Xamarin Hakcday in Melbourne
PPTX
Evolution of C# delegates
PPTX
Async/Await
PPTX
Everything you wanted to know about writing async, concurrent http apps in java
PPTX
From Callback Hell to Async Heaven - Promises!
PPTX
Sync with async
PDF
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
PDF
How to meets Async and Task
PDF
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
PPT
Multithreading, Blocking IO and Async IO
PDF
C# Delegates and Event Handling
PDF
Async await...oh wait!
ODP
Servlet 3.1 Async I/O
PPTX
C# Delegates
PDF
Sync async-blocking-nonblocking-io
PPTX
Think Async in Java 8
PDF
Syncing Async
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
Asynchronous programming from Xamarin Hakcday in Melbourne
Evolution of C# delegates
Async/Await
Everything you wanted to know about writing async, concurrent http apps in java
From Callback Hell to Async Heaven - Promises!
Sync with async
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
How to meets Async and Task
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Multithreading, Blocking IO and Async IO
C# Delegates and Event Handling
Async await...oh wait!
Servlet 3.1 Async I/O
C# Delegates
Sync async-blocking-nonblocking-io
Think Async in Java 8
Syncing Async
Ad

Similar to Using Async in your Mobile Apps - Marek Safar (20)

PPTX
History of asynchronous in .NET
PDF
Asynchronous programming in .net 4.5 with c#
PPTX
Workshop: Async and Parallel in C#
PDF
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
PDF
Understanding Asynchronous JavaScript
PPTX
CSharp for Unity Day2
PDF
Deep Dive async/await in Unity with UniTask(EN)
PPTX
Mobile Application Development class 008
PPTX
Training – Going Async
PPTX
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
PPTX
Unit testing patterns for concurrent code
PPT
Asynchronous in dot net4
PPTX
Ddd melbourne 2011 C# async ctp
PDF
JavaScript for real men
PDF
Angular promises and http
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
PPTX
Async programming and python
PPTX
Windows Phone 8 - 3.5 Async Programming
PDF
Intro to Asynchronous Javascript
PDF
Concurrecny inf sharp
History of asynchronous in .NET
Asynchronous programming in .net 4.5 with c#
Workshop: Async and Parallel in C#
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
Understanding Asynchronous JavaScript
CSharp for Unity Day2
Deep Dive async/await in Unity with UniTask(EN)
Mobile Application Development class 008
Training – Going Async
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Unit testing patterns for concurrent code
Asynchronous in dot net4
Ddd melbourne 2011 C# async ctp
JavaScript for real men
Angular promises and http
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
Async programming and python
Windows Phone 8 - 3.5 Async Programming
Intro to Asynchronous Javascript
Concurrecny inf sharp

More from Xamarin (20)

PDF
Xamarin University Presents: Building Your First Intelligent App with Xamarin...
PDF
Xamarin University Presents: Ship Better Apps with Visual Studio App Center
PDF
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
PDF
Get the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
PDF
Creative Hacking: Delivering React Native App A/B Testing Using CodePush
PDF
Build Better Games with Unity and Microsoft Azure
PDF
Exploring UrhoSharp 3D with Xamarin Workbooks
PDF
Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
PDF
Developer’s Intro to Azure Machine Learning
PDF
Customizing Xamarin.Forms UI
PDF
Session 4 - Xamarin Partner Program, Events and Resources
PDF
Session 3 - Driving Mobile Growth and Profitability
PDF
Session 2 - Emerging Technologies in your Mobile Practice
PDF
Session 1 - Transformative Opportunities in Mobile and Cloud
PDF
SkiaSharp Graphics for Xamarin.Forms
PDF
Building Games for iOS, macOS, and tvOS with Visual Studio and Azure
PDF
Intro to Xamarin.Forms for Visual Studio 2017
PDF
Connected Mobile Apps with Microsoft Azure
PDF
Introduction to Xamarin for Visual Studio 2017
PDF
Building Your First iOS App with Xamarin for Visual Studio
Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Ship Better Apps with Visual Studio App Center
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Creative Hacking: Delivering React Native App A/B Testing Using CodePush
Build Better Games with Unity and Microsoft Azure
Exploring UrhoSharp 3D with Xamarin Workbooks
Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Developer’s Intro to Azure Machine Learning
Customizing Xamarin.Forms UI
Session 4 - Xamarin Partner Program, Events and Resources
Session 3 - Driving Mobile Growth and Profitability
Session 2 - Emerging Technologies in your Mobile Practice
Session 1 - Transformative Opportunities in Mobile and Cloud
SkiaSharp Graphics for Xamarin.Forms
Building Games for iOS, macOS, and tvOS with Visual Studio and Azure
Intro to Xamarin.Forms for Visual Studio 2017
Connected Mobile Apps with Microsoft Azure
Introduction to Xamarin for Visual Studio 2017
Building Your First iOS App with Xamarin for Visual Studio

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
Network Security Unit 5.pdf for BCA BBA.
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Empathic Computing: Creating Shared Understanding
NewMind AI Weekly Chronicles - August'25-Week II
Programs and apps: productivity, graphics, security and other tools
Digital-Transformation-Roadmap-for-Companies.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Chapter 3 Spatial Domain Image Processing.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
Advanced methodologies resolving dimensionality complications for autism neur...
sap open course for s4hana steps from ECC to s4
Spectral efficient network and resource selection model in 5G networks
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Cloud computing and distributed systems.

Using Async in your Mobile Apps - Marek Safar

  • 3. Wikipedia “Asynchronous events are those occurring independently of the main program flow. Asynchronous actions are actions executed in a non-blocking scheme, allowing the main program flow to continue processing”
  • 4. You Should Use Async Today • Your UI always remains responsive • No need to guard against race conditions • No ugly callbacks • Compiler does all the heavy li!ing
  • 6. Async in C# • New major feature of C# 5.0 Makes asynchronous programming a first-class citizen in C# Important part of C# – as significant as LINQ • New async modifier keyword introduced • Methods, lambda expressions, and anonymous methods can be asynchronous • New contextual keyword await introduced
  • 7. Adding Async to Your Codebase • Decorated with new async modifier • Async method must return one of Task, Task<T> or void type • Async anonymous method and lambdas Delegates returning Task, Task<T> or void • Very few restrictions No ref or out parameters allowed No unsafe code No Main async method No async iterators (aka IAsyncEnumerable<T>)
  • 8. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Example: Calculating a Price Asynchronously public  async  Task<int>  CalculatePriceAsync  (Item[]  items) { int  price; //  Calculate  price  asynchronously  and  return  the  value return  price; } public  override  void  ViewDidLoad  () { button.TouchDown  +=  async  (sender,  e)  =>  { //  This  is  asynchronous  handler }; }
  • 9. Await Introduction • Await can be used in async context only Marks a suspension point Can be used anywhere (except catch and finally blocks) Requires awaitable types (Task, Task<T> but can be any custom type) As many as you like inside async block
  • 10. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Calculating a Price Asynchronously public  async  Task<int>  CalculatePriceAsync  (Item[]  items) { using  (var  cmd  =  CreateSqlCommand  (Calculations.TotalPrice,  items))  { using  (var  reader  =  await  cmd.ExecuteReaderAsync  ())  { int  price  =  ReadPrice  (reader); return  price; } } } public  override  void  ViewDidLoad  () { button.TouchDown  +=  async  (sender,  e)  =>  { var  price  =  await  CalculatePriceAsync  (items); priceLabel.Text  =  price.ToString  (); }; }
  • 11. Cancelling an Async Task • CancellationToken controls cancellation process • Async method needs explicitly support it Usually another method overload Task SaveAsync (CancellationToken token) • Caller calls Cancel on CancellationTokenSource Async method stops and returns Task with cancelled state Implementation detail how quickly async method terminates
  • 12. DEMO
  • 13. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Async Language Features public  async  Task  RealAsync  () { //  This  is  real  async  heavy  code  (only  7  awaits  someone  else  will //  certainly  do  better) var  test  =  new  TestClass  (await  CallAsync  ()  |  await  CallAsync  ())  {   Latitude  =  await  GetLatitudeAsync  (await  AnotherAsync  ()),   Roles  =  from  role  in  await  GetRolesAsync  ()  where  role  ==  "agent"  select  role }; .... test  [await  CallAsync  ()]  =  new  int[]  {  33,  await  GetIntAsync  ()  }; ... }
  • 14. Best Practices • Use Async naming suffix for asynchronous methods LoadAsync, SendAsync, etc. Only recommended naming convention • Return Task or Task<T> preferably Task for SaveAsync like methods Task<T> for ReadAsync like methods Leave async void to event handlers only • Support cancellation, if possible
  • 15. Synchronization Context • Framework abstraction over UI toolkit threading model NSRunLoop, DispatchContext in Xamarin.iOS MainLooper in Xamarin.Android Dispatcher in WPF etc. • Await uses synchronization context to restore back suspended context SynchronizationContext::Post method is used Suspension on UI thread resumes back on same UI thread as “expected”
  • 16. Sometimes Things Go Wrong • Async returning Task or Task<T> Task state is set to Faulted Exception is re-thrown when Task is checked (awaited) • Async void Fire and forget asynchrony Exception is thrown on current synchronization context and your app will crash
  • 17. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Exception Handling with Await public  override  void  ViewDidLoad  () { button.TouchDown  +=  async  (sender,  e)  =>  { try  { button.Enabled  =  false; var  price  =  await  CalculatePriceAsync  (items); priceLabel.Text  =  price.ToString  (); }  catch  (Exception  ex)  { //  Handles  price  calculation  error priceLabel.Text  =  "Calculation  failed"; Debug.Print  (ex.ToString  ());  //  Simple  exception  logging }  finally  { button.Enabled  =  true; } }; }
  • 18. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Exception Throwing public  async  Task<int>  CalculatePriceAsync  (Item[]  items) { if  (items  ==  null)  { //  Throw  before  suspension throw  new  ArgumentNullException  ("items"); } ... var  price  =  await  CalculatePriceAsync  (items); if  (price  <  0)  { //  Throw  after  suspension throw  new  ArgumentException  ("Invalid  items"); } ... }
  • 19. Diving Deeper • Await can work with any type which implements the awaiter pattern • Task and Task<T> types do since .NET 4.5 • Any custom type can be made awaitable Has an accessible method called GetAwaiter returning a type which Implements the interface INotifyCompletion Has property IsCompleted of type bool Has method GetResult with no parameters
  • 20. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Custom await Behaviour public  async  Task<int>  SomeAsync  () {    ...    await  3000;  //  This  does  not  compile  unless  we  provide  custom  awaiter    ... } //  Name  of  the  method  is  important static  TaskAwaiter  GetAwaiter  (this  int  millisecondsDelay) {    return  Task.Delay  (millisecondsDelay).GetAwaiter  (); }
  • 21. Async Deadlocks • await restores execution context based on current SynchronizationContext Good for most application code Bad for most library code • Don’t block the UI thread Good old rule still applies in async world Use await when possible
  • 22. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Async Deadlock Example public  async  Task<int>  CalculatePriceAsync  (Item[]  items) { using  (var  cmd  =  CreateSqlCommand  (Calculations.TotalPrice,  items))  { using  (var  r  =  await  cmd.ExecuteReaderAsync  ())  { ..... } } } //  The  method  itself  cannot  be  async public  override  bool  FinishedLaunching  (UIApplication  app,  NSDictionary  options) { .... int  price  =  CalculatePriceAsync  (items).Result;    //  Synchronous  wait //  This  line  won’t  be  reached  if  flow  suspension  occurred }
  • 23. Controlling the Synchronization Context • ConfigureAwait (bool) Controls captured context behaviour • true value - default behaviour Continue execution on context async was called from Important for UI to switch back to UI context • false value Avoids expensive context switching Avoids possible deadlocks on blocking UI
  • 24. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 Async Deadlock Fixed public  async  Task<int>  CalculatePriceAsync  (Item[]  items) { using  (var  cmd  =  CreateSqlCommand  (Calculations.TotalPrice,  items))  { using  (var  r  =  await  cmd.ExecuteReaderAsync  ().ConfigureAwait  (false))  { //  The  context  is  not  restored  but  that’s  fine  for  no  UI  method   } } } //  The  method  itself  cannot  be  async public  override  bool  FinishedLaunching  (UIApplication  app,  NSDictionary  options) { .... int  price  =  CalculatePriceAsync  (items).Result;    //  Synchronous  wait //  Program  continues  when  the  wait  is  signalled }
  • 25. Combinators • Asynchronously wait on multiple asynchronous operations Better than individual awaits of multiple tasks The result can be awaited (Task of Tasks) • Task.WhenAll (IEnumerable<Task>) Completes when all of the individual tasks have completed • Task.WhenAny (IEnumerable<Task>) Completes when any of the individual tasks have completed
  • 26. The Compiler Magic • Compiler does all the “magic” • Local variable and parameters are li!ed into compiler generated type Compiler converts variables and parameters to fields • Any stack values need to be li!ed too Stack needs to be restored a"er suspension • Try-Catch block over any async block • No suspension when awaited task finished
  • 27. Best Practices - Performance • Use ConfigureAwait when you can • Reduce number of local variables Move async block into separate method or lambda expression Pass variables as parameters Avoid deep await usage • Cache Task not task result • Don’t over use async Use async only when appropriate (unreliable tasks, running >50ms) Async has its own overhead
  • 28. Get Your Hands on Async • Async is available today Xamarin.iOS Beta release Xamarin.Android Beta release Xamarin Studio async support • Give us feedback on our new async API Forums Bugzilla Mailing list IRC
  • 29. Q&A