SlideShare a Scribd company logo
Craig Dunn
Developer Evangelist
Xamarin
craig@xamarin.com
@conceptdev
C# async await
for mobile
Mobile Apps
• Need responsive user interfaces
• App features are o!en dependent on:
network access (images, web services)
database functionality or I/O
complex processing on mobile CPUs
any stuff that takes some time
• You want to run these on a different thread to keep the UI
responsive... they should be ASYNCHRONOUS!
Fast!
Long running tasks!
Threads!
All
Responsive User Interfaces
Don’t design
for desktop
Responsive User Interfaces
Instagram Don’t design for desktop
start upload (or here)
so
this
is
FAST
user doesn’t
notice here...
Responsive User Interfaces
Don’t design for desktopInstagram
hit-and-hope
• DO things in the background
• DON’T block the UI thread
• DON’T make users feel like they’re waiting
Responsive User Interfaces
Don’t design for desktop
DEMODEMO1) Download Html string
2) Download Jpeg image
3) Save to Storage
4) Return Html length
Old-style
callbacks
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
Old-style
callbacks
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
Old-style
callbacks
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
Old-style
callbacks
What is “async”?
• Tasks running outside of the main program flow
• Code runs on another thread, so the UI doesn’t block/freeze
• Completion runs on the calling thread, so if you started on the
UI that’s where you’ll be a!er the async task is complete
• async and await syntax in C# 5 takes Task support to the next
level!
Frameworks need to support it on long running tasks
Task Parallel Library (TPL)
has been around a while
Old-style callbacks
• Spaghetti code:
Callbacks are the new “GOTO”
Control flow jumps around in ways that are difficult to read
& understand from the source
Error handling is difficult to implement, required in many
different places
Changes in the chain can have unintended consequences
http://tirania.org/blog/archive/2013/Aug-15.html
Old-style callbacks
• Execute On Main Thread
We need to schedule updates - can’t just access UI objects
directly from background threads
Dispatcher.Invoke (pre RT)
USING ASYNC
async, await, cancellation and error handling
Comparison
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
Comparison
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
Comparison
Async-ified
6) InvokeOnMainThread
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
Comparison
6) InvokeOnMainThread
one place
not required
Async-ified
Comparison
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
old new!
Compiler Magic
http://msdn.microso!.com/en-us/library/vstudio/hh191443.aspx
Compiler Magic
• async keyword informs the compiler that this method needs to be
“munged”
• await keyword indicates a suspension point where a callback
needs to be generated, along with error handling
• Continuations are generated a!er each suspension point
• Error handling (support for enclosing try-catch) is taken care of
• All you need to remember is async and await
and use Tasks
How to use: async?
• async modifier on methods, lambdas and anonymous methods
use Async suffix, eg LoadAsync, SendAsync
return Task or Task<T> preferably
- Task for methods that don’t return a value
- Task<T> to return a value
- void for event handlers only!
void for event handlers
How to use: await?
• await keyword on awaitable objects (Tasks)
only within an async context
marks a suspension point - control is returned to caller
can’t be used in catch or finally blocks
Task, Task<T> or a custom type
get a reference
to the Task first
... or just await
How to use: error handling?
• async Task or Task<T>
Returned Task State == Faulted
Exception re-thrown when task is awaited
• async void methods (event handlers)
Exception is thrown on the current synchronization context
and the app will crash...
How to use: error handling?
• “If a task is the parent of attached child tasks, or if you are
waiting on multiple tasks, then multiple exceptions could be
thrown”
• AggregateException
Loop through, handle or throw as required...
• Cancellation is optional
usually exposed an Async() method overload that takes a
CancellationToken parameter
calling code uses the token
Cancellation.None means it won’t be cancelled by the
caller (useful when the cancellation parameter isn’t optional)
How to use: cancellation?
• Cancellation is optional
cancelled async tasks complete (but time for this to happen
isn’t guaranteed)
How to use: cancellation?
• Specifying a timeout is optional
for HttpClient, set Timeout
some Async methods accept a timeout parameter
more generally, use CancellationToken (timeout)
How to use: timeouts?
• Progress reporting is optional
provide another Async overload with an IProgress<T>
parameter
basic Progress<T> implementation can be used
exposes EventHandler<T> ProgressChanged
How to use: progress reporting?
send events to
track progress
BONUS: Combinators
• Wait on multiple tasks
Task.WhenAll (IEnumerable<Task>)
- requires all the tasks to be completed
Task.WhenAny(IEnumerable<Task>)
- returns when any of the tasks completes
this kind of
loop fine for
small numbers
of Tasks
WARNING: Await, and UI, and deadlocks
http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx
MOAR MOBILE
iOS & Android too!
.NET BCL APIs
• Lots of .NET APIs support async; for example:
HttpClient.GetStringAsync()
HttpClient.PostAsync()
FileStream.ReadAsync()
FileStream.CopyToAsync()
• and many more...
Windows Store and Phone apps
only have async APIs
Xamarin.iOS
• updated iOS APIs to be async; some examples:
ALAssetsLibrary.WriteImageToSavedPhotosAlbumAsync()
ALAsset.SetImageDataAsync()
SKStoreProductViewController.LoadProductAsync()
CLGeocoder.GeocodeAddress()
NSUrlConnection.SendRequestAsync()
and many more... 174 async iOS native APIs
Xamarin.Android
• updated Android APIs to be async; some examples:
Android.Net.Http.AndroidHttpClient.ExecuteAsync()
Android.Bluetooth.BluetoothServerSocket.AcceptAsync()
Android.Graphics.BitmapFactory.DecodeFileAsync()
Android.Locations.Geocoder.GetFromLocationAsync()
Java.IO.File.ListAsync()
and many more... 337 async Android native APIs
Xamarin APIs
• Xamarin.Mobile
Geolocator.GetPositionAsync()
Contact.SaveThumbnailAsync()
• Xamarin.Auth
FormAuthenticator.SignInAsync()
Request.GetResponseAsync(cancellationToken)
• and many more...
Xamarin cross-platform libraries
Xamarin Component Store
• Many components already
offer async APIs, eg. Parse!
Powerful, easy to use components
http://components.xamarin.com
DEMODEMO
ParseTodo
Other tricks...
• Creating your own async Tasks
eg. how you could async-ify WebClient
http://developer.nokia.com/Community/Wiki/
Asynchronous_Programming_For_Windows_Phone_8
Other tricks...
• Creating your own async Tasks
Don’t await... give it a try
• Available in .NET 4.5 for Windows Store apps, Windows 8,
Windows Phone, etc.
• Also available programming in C# iOS & Android using Xamarin!
xamarin.com/download
Questions?
Developer Evangelist
Xamarin
craig@xamarin.com
@conceptdev
Craig Dunn

More Related Content

What's hot

CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
Spiffy
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
Doug Jones
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed 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 2012
Sri Kanth
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
Chris Dufour
 
CSharp 5 Async
CSharp 5 AsyncCSharp 5 Async
CSharp 5 Async
Valdis Iljuconoks
 
Anatomy of a Reactive Application
Anatomy of a Reactive ApplicationAnatomy of a Reactive Application
Anatomy of a Reactive Application
Mark Wilson
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
Ayush Sharma
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
Marcus Denker
 
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
Marcus Denker
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
Marcus Denker
 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps
Particular Software
 
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
Tomaž Zaman
 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013
slandelle
 
Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5
Marcus Denker
 
Using assm in service object
Using assm in service object Using assm in service object
Using assm in service object
Railwaymen
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
Particular Software
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
Christophe Marchal
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS Lambda
Naresha K
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB
 

What's hot (20)

CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
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
 
CSharp 5 Async
CSharp 5 AsyncCSharp 5 Async
CSharp 5 Async
 
Anatomy of a Reactive Application
Anatomy of a Reactive ApplicationAnatomy of a Reactive Application
Anatomy of a Reactive Application
 
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
 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps
 
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
 
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
 
Using assm in service object
Using assm in service object Using assm in service object
Using assm in service object
 
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
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS Lambda
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
 

Similar to Async Await for Mobile Apps

Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
Betclic Everest Group Tech Team
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
Pratik Khasnabis
 
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
Xamarin
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
Soacat Blogspot
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
Paul van Zyl
 
Postmortem of a uwp xaml application development
Postmortem of a uwp xaml application developmentPostmortem of a uwp xaml application development
Postmortem of a uwp xaml application development
David Catuhe
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
Pierre-Luc Maheu
 
Advanced android app lifecycle + Patterns
Advanced android app lifecycle + PatternsAdvanced android app lifecycle + Patterns
Advanced android app lifecycle + Patterns
bryan costanich
 
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
 Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Daniel Gallego Vico
 
Mobile Application Development class 008
Mobile Application Development class 008Mobile Application Development class 008
Mobile Application Development class 008
Dr. Mazin Mohamed alkathiri
 
Runtime performance
Runtime performanceRuntime performance
Runtime performance
Eliran Eliassy
 
Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData
Oleg Tsal-Tsalko
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
Juti Noppornpitak
 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
Ruslan Novikov
 
Production-ready Software
Production-ready SoftwareProduction-ready Software
Production-ready Software
Uwe Friedrichsen
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 
Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadin
Petter Holmström
 

Similar to Async Await for Mobile Apps (20)

Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
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
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
 
Postmortem of a uwp xaml application development
Postmortem of a uwp xaml application developmentPostmortem of a uwp xaml application development
Postmortem of a uwp xaml application development
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
Advanced android app lifecycle + Patterns
Advanced android app lifecycle + PatternsAdvanced android app lifecycle + Patterns
Advanced android app lifecycle + Patterns
 
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
 Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
 
Mobile Application Development class 008
Mobile Application Development class 008Mobile Application Development class 008
Mobile Application Development class 008
 
Runtime performance
Runtime performanceRuntime performance
Runtime performance
 
Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData Develop modern apps using Spring ecosystem at time of BigData
Develop modern apps using Spring ecosystem at time of BigData
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
 
Production-ready Software
Production-ready SoftwareProduction-ready Software
Production-ready Software
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadin
 

More from Craig Dunn

Visual Studio for Mac (AltConf 2017)
Visual Studio for Mac (AltConf 2017)Visual Studio for Mac (AltConf 2017)
Visual Studio for Mac (AltConf 2017)
Craig Dunn
 
EastBay.net Building Mobile Apps with Xamarin and Visual Studio
EastBay.net Building Mobile Apps with Xamarin and Visual StudioEastBay.net Building Mobile Apps with Xamarin and Visual Studio
EastBay.net Building Mobile Apps with Xamarin and Visual Studio
Craig Dunn
 
Introduction to iOS 9 (Xamarin Evolve 2016)
Introduction to iOS 9 (Xamarin Evolve 2016)Introduction to iOS 9 (Xamarin Evolve 2016)
Introduction to iOS 9 (Xamarin Evolve 2016)
Craig Dunn
 
Xamarin for iOS developers
Xamarin for iOS developersXamarin for iOS developers
Xamarin for iOS developers
Craig Dunn
 
Introduction to Xamarin.Forms 2.x
Introduction to Xamarin.Forms 2.xIntroduction to Xamarin.Forms 2.x
Introduction to Xamarin.Forms 2.x
Craig Dunn
 
Xamarin DevDays Portland - iOS 9
Xamarin DevDays Portland - iOS 9Xamarin DevDays Portland - iOS 9
Xamarin DevDays Portland - iOS 9
Craig Dunn
 
Wearables with C# and Xamarin
Wearables with C# and XamarinWearables with C# and Xamarin
Wearables with C# and Xamarin
Craig Dunn
 
What's New Xamarin.Forms 1.3
What's New Xamarin.Forms 1.3What's New Xamarin.Forms 1.3
What's New Xamarin.Forms 1.3
Craig Dunn
 
Your First Xamarin.Forms App
Your First Xamarin.Forms AppYour First Xamarin.Forms App
Your First Xamarin.Forms App
Craig Dunn
 
Introduction to iOS with C# using Xamarin
Introduction to iOS with C# using XamarinIntroduction to iOS with C# using Xamarin
Introduction to iOS with C# using Xamarin
Craig Dunn
 
Introduction to Android with C# using Xamarin
Introduction to Android with C# using XamarinIntroduction to Android with C# using Xamarin
Introduction to Android with C# using Xamarin
Craig Dunn
 
iOS & Android apps using Parse and Xamarin
iOS & Android apps using Parse and XamariniOS & Android apps using Parse and Xamarin
iOS & Android apps using Parse and Xamarin
Craig Dunn
 
Azure Mobile Services - more than just cloud data
Azure Mobile Services - more than just cloud dataAzure Mobile Services - more than just cloud data
Azure Mobile Services - more than just cloud data
Craig Dunn
 
Cloud-enabling iOS & Android apps with C# (using Xamarin)
Cloud-enabling iOS & Android apps with C# (using Xamarin)Cloud-enabling iOS & Android apps with C# (using Xamarin)
Cloud-enabling iOS & Android apps with C# (using Xamarin)
Craig Dunn
 
Cloudy with a Chance of Cross Platform (for Bay.NET)
Cloudy with a Chance of Cross Platform (for Bay.NET)Cloudy with a Chance of Cross Platform (for Bay.NET)
Cloudy with a Chance of Cross Platform (for Bay.NET)
Craig Dunn
 
Xamarin v.Now
Xamarin v.NowXamarin v.Now
Xamarin v.Now
Craig Dunn
 
C# everywhere
C# everywhereC# everywhere
C# everywhere
Craig Dunn
 
Mono for Android... for Google Devs
Mono for Android... for Google DevsMono for Android... for Google Devs
Mono for Android... for Google Devs
Craig Dunn
 
PassKit on iOS6
PassKit on iOS6PassKit on iOS6
PassKit on iOS6
Craig Dunn
 
OzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousOzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furious
Craig Dunn
 

More from Craig Dunn (20)

Visual Studio for Mac (AltConf 2017)
Visual Studio for Mac (AltConf 2017)Visual Studio for Mac (AltConf 2017)
Visual Studio for Mac (AltConf 2017)
 
EastBay.net Building Mobile Apps with Xamarin and Visual Studio
EastBay.net Building Mobile Apps with Xamarin and Visual StudioEastBay.net Building Mobile Apps with Xamarin and Visual Studio
EastBay.net Building Mobile Apps with Xamarin and Visual Studio
 
Introduction to iOS 9 (Xamarin Evolve 2016)
Introduction to iOS 9 (Xamarin Evolve 2016)Introduction to iOS 9 (Xamarin Evolve 2016)
Introduction to iOS 9 (Xamarin Evolve 2016)
 
Xamarin for iOS developers
Xamarin for iOS developersXamarin for iOS developers
Xamarin for iOS developers
 
Introduction to Xamarin.Forms 2.x
Introduction to Xamarin.Forms 2.xIntroduction to Xamarin.Forms 2.x
Introduction to Xamarin.Forms 2.x
 
Xamarin DevDays Portland - iOS 9
Xamarin DevDays Portland - iOS 9Xamarin DevDays Portland - iOS 9
Xamarin DevDays Portland - iOS 9
 
Wearables with C# and Xamarin
Wearables with C# and XamarinWearables with C# and Xamarin
Wearables with C# and Xamarin
 
What's New Xamarin.Forms 1.3
What's New Xamarin.Forms 1.3What's New Xamarin.Forms 1.3
What's New Xamarin.Forms 1.3
 
Your First Xamarin.Forms App
Your First Xamarin.Forms AppYour First Xamarin.Forms App
Your First Xamarin.Forms App
 
Introduction to iOS with C# using Xamarin
Introduction to iOS with C# using XamarinIntroduction to iOS with C# using Xamarin
Introduction to iOS with C# using Xamarin
 
Introduction to Android with C# using Xamarin
Introduction to Android with C# using XamarinIntroduction to Android with C# using Xamarin
Introduction to Android with C# using Xamarin
 
iOS & Android apps using Parse and Xamarin
iOS & Android apps using Parse and XamariniOS & Android apps using Parse and Xamarin
iOS & Android apps using Parse and Xamarin
 
Azure Mobile Services - more than just cloud data
Azure Mobile Services - more than just cloud dataAzure Mobile Services - more than just cloud data
Azure Mobile Services - more than just cloud data
 
Cloud-enabling iOS & Android apps with C# (using Xamarin)
Cloud-enabling iOS & Android apps with C# (using Xamarin)Cloud-enabling iOS & Android apps with C# (using Xamarin)
Cloud-enabling iOS & Android apps with C# (using Xamarin)
 
Cloudy with a Chance of Cross Platform (for Bay.NET)
Cloudy with a Chance of Cross Platform (for Bay.NET)Cloudy with a Chance of Cross Platform (for Bay.NET)
Cloudy with a Chance of Cross Platform (for Bay.NET)
 
Xamarin v.Now
Xamarin v.NowXamarin v.Now
Xamarin v.Now
 
C# everywhere
C# everywhereC# everywhere
C# everywhere
 
Mono for Android... for Google Devs
Mono for Android... for Google DevsMono for Android... for Google Devs
Mono for Android... for Google Devs
 
PassKit on iOS6
PassKit on iOS6PassKit on iOS6
PassKit on iOS6
 
OzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousOzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furious
 

Recently uploaded

Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 

Recently uploaded (20)

Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 

Async Await for Mobile Apps

  • 2. Mobile Apps • Need responsive user interfaces • App features are o!en dependent on: network access (images, web services) database functionality or I/O complex processing on mobile CPUs any stuff that takes some time • You want to run these on a different thread to keep the UI responsive... they should be ASYNCHRONOUS! Fast! Long running tasks! Threads! All
  • 4. Responsive User Interfaces Instagram Don’t design for desktop start upload (or here) so this is FAST user doesn’t notice here...
  • 5. Responsive User Interfaces Don’t design for desktopInstagram hit-and-hope
  • 6. • DO things in the background • DON’T block the UI thread • DON’T make users feel like they’re waiting Responsive User Interfaces Don’t design for desktop
  • 7. DEMODEMO1) Download Html string 2) Download Jpeg image 3) Save to Storage 4) Return Html length
  • 8. Old-style callbacks 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread Callback Hell
  • 9. Old-style callbacks 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread Callback Hell
  • 10. Old-style callbacks 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread Callback Hell
  • 11. 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread Callback Hell Old-style callbacks
  • 12. What is “async”? • Tasks running outside of the main program flow • Code runs on another thread, so the UI doesn’t block/freeze • Completion runs on the calling thread, so if you started on the UI that’s where you’ll be a!er the async task is complete • async and await syntax in C# 5 takes Task support to the next level! Frameworks need to support it on long running tasks Task Parallel Library (TPL) has been around a while
  • 13. Old-style callbacks • Spaghetti code: Callbacks are the new “GOTO” Control flow jumps around in ways that are difficult to read & understand from the source Error handling is difficult to implement, required in many different places Changes in the chain can have unintended consequences http://tirania.org/blog/archive/2013/Aug-15.html
  • 14. Old-style callbacks • Execute On Main Thread We need to schedule updates - can’t just access UI objects directly from background threads Dispatcher.Invoke (pre RT)
  • 15. USING ASYNC async, await, cancellation and error handling
  • 16. Comparison 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread Callback Hell
  • 17. Comparison 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread Callback Hell
  • 18. 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length Comparison Async-ified 6) InvokeOnMainThread
  • 19. 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length Comparison 6) InvokeOnMainThread one place not required Async-ified
  • 20. Comparison 1) Download Html string 2) Download Jpeg image 3) Save to Photo Album 5) Error Handling 4) Return Html length 6) InvokeOnMainThread old new!
  • 22. Compiler Magic • async keyword informs the compiler that this method needs to be “munged” • await keyword indicates a suspension point where a callback needs to be generated, along with error handling • Continuations are generated a!er each suspension point • Error handling (support for enclosing try-catch) is taken care of • All you need to remember is async and await and use Tasks
  • 23. How to use: async? • async modifier on methods, lambdas and anonymous methods use Async suffix, eg LoadAsync, SendAsync return Task or Task<T> preferably - Task for methods that don’t return a value - Task<T> to return a value - void for event handlers only! void for event handlers
  • 24. How to use: await? • await keyword on awaitable objects (Tasks) only within an async context marks a suspension point - control is returned to caller can’t be used in catch or finally blocks Task, Task<T> or a custom type get a reference to the Task first ... or just await
  • 25. How to use: error handling? • async Task or Task<T> Returned Task State == Faulted Exception re-thrown when task is awaited • async void methods (event handlers) Exception is thrown on the current synchronization context and the app will crash...
  • 26. How to use: error handling? • “If a task is the parent of attached child tasks, or if you are waiting on multiple tasks, then multiple exceptions could be thrown” • AggregateException Loop through, handle or throw as required...
  • 27. • Cancellation is optional usually exposed an Async() method overload that takes a CancellationToken parameter calling code uses the token Cancellation.None means it won’t be cancelled by the caller (useful when the cancellation parameter isn’t optional) How to use: cancellation?
  • 28. • Cancellation is optional cancelled async tasks complete (but time for this to happen isn’t guaranteed) How to use: cancellation?
  • 29. • Specifying a timeout is optional for HttpClient, set Timeout some Async methods accept a timeout parameter more generally, use CancellationToken (timeout) How to use: timeouts?
  • 30. • Progress reporting is optional provide another Async overload with an IProgress<T> parameter basic Progress<T> implementation can be used exposes EventHandler<T> ProgressChanged How to use: progress reporting? send events to track progress
  • 31. BONUS: Combinators • Wait on multiple tasks Task.WhenAll (IEnumerable<Task>) - requires all the tasks to be completed Task.WhenAny(IEnumerable<Task>) - returns when any of the tasks completes this kind of loop fine for small numbers of Tasks
  • 32. WARNING: Await, and UI, and deadlocks http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx
  • 33. MOAR MOBILE iOS & Android too!
  • 34. .NET BCL APIs • Lots of .NET APIs support async; for example: HttpClient.GetStringAsync() HttpClient.PostAsync() FileStream.ReadAsync() FileStream.CopyToAsync() • and many more... Windows Store and Phone apps only have async APIs
  • 35. Xamarin.iOS • updated iOS APIs to be async; some examples: ALAssetsLibrary.WriteImageToSavedPhotosAlbumAsync() ALAsset.SetImageDataAsync() SKStoreProductViewController.LoadProductAsync() CLGeocoder.GeocodeAddress() NSUrlConnection.SendRequestAsync() and many more... 174 async iOS native APIs
  • 36. Xamarin.Android • updated Android APIs to be async; some examples: Android.Net.Http.AndroidHttpClient.ExecuteAsync() Android.Bluetooth.BluetoothServerSocket.AcceptAsync() Android.Graphics.BitmapFactory.DecodeFileAsync() Android.Locations.Geocoder.GetFromLocationAsync() Java.IO.File.ListAsync() and many more... 337 async Android native APIs
  • 37. Xamarin APIs • Xamarin.Mobile Geolocator.GetPositionAsync() Contact.SaveThumbnailAsync() • Xamarin.Auth FormAuthenticator.SignInAsync() Request.GetResponseAsync(cancellationToken) • and many more... Xamarin cross-platform libraries
  • 38. Xamarin Component Store • Many components already offer async APIs, eg. Parse! Powerful, easy to use components http://components.xamarin.com
  • 40. Other tricks... • Creating your own async Tasks eg. how you could async-ify WebClient http://developer.nokia.com/Community/Wiki/ Asynchronous_Programming_For_Windows_Phone_8
  • 41. Other tricks... • Creating your own async Tasks
  • 42. Don’t await... give it a try • Available in .NET 4.5 for Windows Store apps, Windows 8, Windows Phone, etc. • Also available programming in C# iOS & Android using Xamarin! xamarin.com/download