SlideShare a Scribd company logo
1 of 29
Download to read offline
Craig Dunn
Developer Evangelist
Xamarin
craig@xamarin.com
@conceptdev
C# async await
Mobile Apps
ā€¢ Need responsive user interfaces
ā€¢ App features are o!en dependent on:
network access
database functionality or I/O
complex processing on mobile CPUs
stuļ¬€ that takes some time
ā€¢ You want to run these on a diļ¬€erent thread to keep the UI
responsive... they should be ASYNCHRONOUS!
Fast!
Long running tasks!
Threads!
All
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
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
Old-style callbacks
ā€¢ Spaghetti code:
Callbacks are the new ā€œGOTOā€
Control flow jumps around in ways that are diļ¬€icult to read
& understand from the source
Error handling is diļ¬€icult to implement, required in many
diļ¬€erent places
Changes in the chain can have unintended consequences
http://tirania.org/blog/archive/2013/Aug-15.html
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
.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
oļ¬€er async APIs, eg. Parse!
Powerful, easy to use components
http://components.xamarin.com
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
LOL =D
Compiler Magic
ā€¢ async keyword informs the compiler that this method needs to be
ā€œmungedā€ (my term)
ā€¢ 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 suļ¬€ix, 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...
ā€¢ Cancellation is optional
provide another Async method, usually an overload, that
takes a CancellationToken parameter
caller uses the token
async tasks complete with Faulted state (time for this to
happen isnā€™t guaranteed)
Cancellation.None means it wonā€™t be cancelled by the
caller
How to use: cancellation?
ā€¢ 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
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

Viewers also liked

Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
Ā 
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
Ā 
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# Async on iOS and Android - Miguel de Icaza, CTO of XamarinC# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# Async on iOS and Android - Miguel de Icaza, CTO of XamarinXamarin
Ā 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
Ā 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!Thomas Pierrain
Ā 
The Future of C# and .NET Framework
The Future of C# and .NET FrameworkThe Future of C# and .NET Framework
The Future of C# and .NET FrameworkėŖ…ģ‹  ź¹€
Ā 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
Ā 
Python ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio Code
Python ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio CodePython ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio Code
Python ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio CodeėŖ…ģ‹  ź¹€
Ā 

Viewers also liked (11)

Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
Ā 
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
Ā 
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# Async on iOS and Android - Miguel de Icaza, CTO of XamarinC# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
Ā 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Ā 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
Ā 
The Future of C# and .NET Framework
The Future of C# and .NET FrameworkThe Future of C# and .NET Framework
The Future of C# and .NET Framework
Ā 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
Ā 
Python ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio Code
Python ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio CodePython ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio Code
Python ź°œė°œģžė„¼ ģœ„ķ•œ ģµœģƒģ˜ ė¬“ė£Œ ź°œė°œ ė„źµ¬ Visual Studioģ™€ Visual Studio Code
Ā 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
Ā 

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 StudioCraig 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 developersCraig Dunn
Ā 
Introduction to Xamarin.Forms 2.x
Introduction to Xamarin.Forms 2.xIntroduction to Xamarin.Forms 2.x
Introduction to Xamarin.Forms 2.xCraig Dunn
Ā 
Xamarin DevDays Portland - iOS 9
Xamarin DevDays Portland - iOS 9Xamarin DevDays Portland - iOS 9
Xamarin DevDays Portland - iOS 9Craig Dunn
Ā 
Wearables with C# and Xamarin
Wearables with C# and XamarinWearables with C# and Xamarin
Wearables with C# and XamarinCraig 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.3Craig Dunn
Ā 
Your First Xamarin.Forms App
Your First Xamarin.Forms AppYour First Xamarin.Forms App
Your First Xamarin.Forms AppCraig 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 XamarinCraig 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 XamarinCraig 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 XamarinCraig 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 dataCraig 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.NowCraig Dunn
Ā 
Mono for Android... for Google Devs
Mono for Android... for Google DevsMono for Android... for Google Devs
Mono for Android... for Google DevsCraig Dunn
Ā 
PassKit on iOS6
PassKit on iOS6PassKit on iOS6
PassKit on iOS6Craig Dunn
Ā 
OzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousOzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousCraig Dunn
Ā 
OzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousOzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousCraig 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
Ā 
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
Ā 
OzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furiousOzAltNet Fast-ANDroid-furious
OzAltNet Fast-ANDroid-furious
Ā 

Recently uploaded

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
Ā 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
Ā 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
Ā 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
Ā 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
Ā 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
Ā 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
Ā 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
Ā 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
Ā 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vƔzquez
Ā 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
Ā 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
Ā 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
Ā 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
Ā 

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
Ā 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Ā 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
Ā 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Ā 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Ā 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
Ā 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
Ā 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
Ā 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
Ā 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Ā 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
Ā 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Ā 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Ā 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Ā 

C# 5 async-await (for EastBay.NET)

  • 2. Mobile Apps ā€¢ Need responsive user interfaces ā€¢ App features are o!en dependent on: network access database functionality or I/O complex processing on mobile CPUs stuļ¬€ that takes some time ā€¢ You want to run these on a diļ¬€erent thread to keep the UI responsive... they should be ASYNCHRONOUS! Fast! Long running tasks! Threads! All
  • 3. DEMODEMO1) Download Html string 2) Download Jpeg image 3) Save to Storage 4) Return Html length
  • 4. 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
  • 5. 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
  • 6. Old-style callbacks ā€¢ Spaghetti code: Callbacks are the new ā€œGOTOā€ Control flow jumps around in ways that are diļ¬€icult to read & understand from the source Error handling is diļ¬€icult to implement, required in many diļ¬€erent places Changes in the chain can have unintended consequences http://tirania.org/blog/archive/2013/Aug-15.html
  • 7. 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
  • 8. .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
  • 9. 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
  • 10. 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
  • 11. Xamarin APIs ā€¢ Xamarin.Mobile Geolocator.GetPositionAsync() Contact.SaveThumbnailAsync() ā€¢ Xamarin.Auth FormAuthenticator.SignInAsync() Request.GetResponseAsync(cancellationToken) ā€¢ and many more... Xamarin cross-platform libraries
  • 12. Xamarin Component Store ā€¢ Many components already oļ¬€er async APIs, eg. Parse! Powerful, easy to use components http://components.xamarin.com
  • 13. USING ASYNC async, await, cancellation and error handling
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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!
  • 20. Compiler Magic ā€¢ async keyword informs the compiler that this method needs to be ā€œmungedā€ (my term) ā€¢ 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
  • 21. How to use: async? ā€¢ async modifier on methods, lambdas and anonymous methods use Async suļ¬€ix, 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
  • 22. 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
  • 23. 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...
  • 24. ā€¢ Cancellation is optional provide another Async method, usually an overload, that takes a CancellationToken parameter caller uses the token async tasks complete with Faulted state (time for this to happen isnā€™t guaranteed) Cancellation.None means it wonā€™t be cancelled by the caller How to use: cancellation?
  • 25. ā€¢ 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
  • 26. 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
  • 27. WARNING: Await, and UI, and deadlocks http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx
  • 28. 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