SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
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
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

Más contenido relacionado

La actualidad más candente

Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the ServerDoug Jones
 
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
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Sri Kanth
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Anatomy of a Reactive Application
Anatomy of a Reactive ApplicationAnatomy of a Reactive Application
Anatomy of a Reactive ApplicationMark Wilson
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection PromisesDynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection PromisesMarcus Denker
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakMarcus Denker
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakMarcus Denker
 
Using assm in service object
Using assm in service object Using assm in service object
Using assm in service object Railwaymen
 
Continuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorksContinuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorksTomaž Zaman
 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Particular Software
 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013slandelle
 
Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5Marcus Denker
 
DRAKON Visual Language: Tutorial. Part 2
DRAKON Visual Language: Tutorial. Part 2DRAKON Visual Language: Tutorial. Part 2
DRAKON Visual Language: Tutorial. Part 2Stepan Mitkin
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
 

La actualidad más candente (20)

Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
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
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Anatomy of a Reactive Application
Anatomy of a Reactive ApplicationAnatomy of a Reactive Application
Anatomy of a Reactive Application
 
CSharp 5 Async
CSharp 5 AsyncCSharp 5 Async
CSharp 5 Async
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection PromisesDynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection Promises
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
 
Using assm in service object
Using assm in service object Using assm in service object
Using assm in service object
 
Continuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorksContinuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorks
 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps
 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013
 
Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5
 
DRAKON Visual Language: Tutorial. Part 2
DRAKON Visual Language: Tutorial. Part 2DRAKON Visual Language: Tutorial. Part 2
DRAKON Visual Language: Tutorial. Part 2
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 

Destacado

C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at XamarinC# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at XamarinXamarin
 
Asynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneAsynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneFilip Ekberg
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegatesmbaric
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Baruch Sadogursky
 
From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!Gil Tayar
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...Lviv Startup Club
 
How to meets Async and Task
How to meets Async and TaskHow to meets Async and Task
How to meets Async and TaskKouji Matsui
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainPromises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainHans-Gunther Schmidt
 
Multithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IOMultithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IODirecti Group
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/OSimone Bordet
 
Sync async-blocking-nonblocking-io
Sync async-blocking-nonblocking-ioSync async-blocking-nonblocking-io
Sync async-blocking-nonblocking-ioCheoloh Bae
 
Syncing Async
Syncing AsyncSyncing Async
Syncing AsyncFITC
 

Destacado (18)

C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at XamarinC# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
 
Asynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneAsynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in Melbourne
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegates
 
Async/Await
Async/AwaitAsync/Await
Async/Await
 
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
 
From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
 
How to meets Async and Task
How to meets Async and TaskHow to meets Async and Task
How to meets Async and Task
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainPromises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
 
Multithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IOMultithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IO
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/O
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Sync async-blocking-nonblocking-io
Sync async-blocking-nonblocking-ioSync async-blocking-nonblocking-io
Sync async-blocking-nonblocking-io
 
Think Async in Java 8
Think Async in Java 8Think Async in Java 8
Think Async in Java 8
 
Syncing Async
Syncing AsyncSyncing Async
Syncing Async
 

Similar a Using Async in your Mobile Apps - Marek Safar

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4Wei Sun
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel ZikmundKarel Zikmund
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 

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

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Mobile Application Development class 008
Mobile Application Development class 008Mobile Application Development class 008
Mobile Application Development class 008
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
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
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 

Más de Xamarin

Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Building Your First Intelligent App with Xamarin...Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Building Your First Intelligent App with Xamarin...Xamarin
 
Xamarin University Presents: Ship Better Apps with Visual Studio App Center
Xamarin University Presents: Ship Better Apps with Visual Studio App CenterXamarin University Presents: Ship Better Apps with Visual Studio App Center
Xamarin University Presents: Ship Better Apps with Visual Studio App CenterXamarin
 
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinGet the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinXamarin
 
Get the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for XamarinGet the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for XamarinXamarin
 
Creative Hacking: Delivering React Native App A/B Testing Using CodePush
Creative Hacking: Delivering React Native App A/B Testing Using CodePushCreative Hacking: Delivering React Native App A/B Testing Using CodePush
Creative Hacking: Delivering React Native App A/B Testing Using CodePushXamarin
 
Build Better Games with Unity and Microsoft Azure
Build Better Games with Unity and Microsoft AzureBuild Better Games with Unity and Microsoft Azure
Build Better Games with Unity and Microsoft AzureXamarin
 
Exploring UrhoSharp 3D with Xamarin Workbooks
Exploring UrhoSharp 3D with Xamarin WorkbooksExploring UrhoSharp 3D with Xamarin Workbooks
Exploring UrhoSharp 3D with Xamarin WorkbooksXamarin
 
Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Desktop Developer’s Guide to Mobile with Visual Studio Tools for XamarinDesktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Desktop Developer’s Guide to Mobile with Visual Studio Tools for XamarinXamarin
 
Developer’s Intro to Azure Machine Learning
Developer’s Intro to Azure Machine LearningDeveloper’s Intro to Azure Machine Learning
Developer’s Intro to Azure Machine LearningXamarin
 
Customizing Xamarin.Forms UI
Customizing Xamarin.Forms UICustomizing Xamarin.Forms UI
Customizing Xamarin.Forms UIXamarin
 
Session 4 - Xamarin Partner Program, Events and Resources
Session 4 - Xamarin Partner Program, Events and ResourcesSession 4 - Xamarin Partner Program, Events and Resources
Session 4 - Xamarin Partner Program, Events and ResourcesXamarin
 
Session 3 - Driving Mobile Growth and Profitability
Session 3 - Driving Mobile Growth and ProfitabilitySession 3 - Driving Mobile Growth and Profitability
Session 3 - Driving Mobile Growth and ProfitabilityXamarin
 
Session 2 - Emerging Technologies in your Mobile Practice
Session 2 - Emerging Technologies in your Mobile PracticeSession 2 - Emerging Technologies in your Mobile Practice
Session 2 - Emerging Technologies in your Mobile PracticeXamarin
 
Session 1 - Transformative Opportunities in Mobile and Cloud
Session 1 - Transformative Opportunities in Mobile and Cloud Session 1 - Transformative Opportunities in Mobile and Cloud
Session 1 - Transformative Opportunities in Mobile and Cloud Xamarin
 
SkiaSharp Graphics for Xamarin.Forms
SkiaSharp Graphics for Xamarin.FormsSkiaSharp Graphics for Xamarin.Forms
SkiaSharp Graphics for Xamarin.FormsXamarin
 
Building Games for iOS, macOS, and tvOS with Visual Studio and Azure
Building Games for iOS, macOS, and tvOS with Visual Studio and AzureBuilding Games for iOS, macOS, and tvOS with Visual Studio and Azure
Building Games for iOS, macOS, and tvOS with Visual Studio and AzureXamarin
 
Intro to Xamarin.Forms for Visual Studio 2017
Intro to Xamarin.Forms for Visual Studio 2017Intro to Xamarin.Forms for Visual Studio 2017
Intro to Xamarin.Forms for Visual Studio 2017Xamarin
 
Connected Mobile Apps with Microsoft Azure
Connected Mobile Apps with Microsoft AzureConnected Mobile Apps with Microsoft Azure
Connected Mobile Apps with Microsoft AzureXamarin
 
Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Xamarin
 
Building Your First iOS App with Xamarin for Visual Studio
Building Your First iOS App with Xamarin for Visual StudioBuilding Your First iOS App with Xamarin for Visual Studio
Building Your First iOS App with Xamarin for Visual StudioXamarin
 

Más de Xamarin (20)

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

Último

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
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
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 Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
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
 
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
 

Último (20)

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
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
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 Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
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
 
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
 
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
 
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
 

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
  • 5.
  • 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