Async Await for Mobile Apps
-
Upload
craig-dunn -
Category
Technology
-
view
1.755 -
download
9
description
Transcript of Async Await for Mobile Apps
![Page 2: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/2.jpg)
Mobile Apps
• Need responsive user interfaces• App features are o!en dependent on:
network access (images, web services)database functionality or I/Ocomplex processing on mobile CPUsany 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
![Page 3: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/3.jpg)
Responsive User Interfaces
Don’t designfor desktop
![Page 4: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/4.jpg)
Responsive User InterfacesInstagram Don’t design for desktop
start upload (or here)
so this is FAST
user doesn’t notice here...
![Page 5: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/5.jpg)
Responsive User InterfacesDon’t design for desktopInstagram
hit-and-hope
![Page 6: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/6.jpg)
• DO things in the background
• DON’T block the UI thread
• DON’T make users feel like they’re waiting
Responsive User InterfacesDon’t design for desktop
![Page 7: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/7.jpg)
DEMODEMO1) Download Html string2) Download Jpeg image3) Save to Storage4) Return Html length
![Page 8: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/8.jpg)
Old-style callbacks
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
Callback Hell
![Page 9: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/9.jpg)
Old-style callbacks
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
Callback Hell
![Page 10: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/10.jpg)
Old-style callbacks
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
Callback Hell
![Page 11: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/11.jpg)
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
Callback Hell
Old-style callbacks
![Page 12: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/12.jpg)
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
![Page 13: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/13.jpg)
Old-style callbacks
• Spaghetti code:
Callbacks are the new “GOTO”Control flow jumps around in ways that are difficult to read & understand from the sourceError handling is difficult to implement, required in many different placesChanges in the chain can have unintended consequences
http://tirania.org/blog/archive/2013/Aug-15.html
![Page 14: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/14.jpg)
Old-style callbacks
• Execute On Main ThreadWe need to schedule updates - can’t just access UI objects directly from background threadsDispatcher.Invoke (pre RT)
![Page 15: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/15.jpg)
USING ASYNCasync, await, cancellation and error handling
![Page 16: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/16.jpg)
Comparison
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
Callback Hell
![Page 17: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/17.jpg)
Comparison
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
Callback Hell
![Page 18: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/18.jpg)
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
Comparison
Async-ified
6) InvokeOnMainThread
![Page 19: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/19.jpg)
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
Comparison
6) InvokeOnMainThreadone place
not required
Async-ified
![Page 20: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/20.jpg)
Comparison
1) Download Html string2) Download Jpeg image3) Save to Photo Album
5) Error Handling4) Return Html length
6) InvokeOnMainThread
old new!
![Page 21: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/21.jpg)
Compiler Magic
http://msdn.microso!.com/en-us/library/vstudio/hh191443.aspx
![Page 22: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/22.jpg)
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 awaitand use Tasks
![Page 23: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/23.jpg)
How to use: async?• async modifier on methods, lambdas and anonymous methods
use Async suffix, eg LoadAsync, SendAsyncreturn 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
![Page 24: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/24.jpg)
How to use: await?• await keyword on awaitable objects (Tasks)
only within an async contextmarks a suspension point - control is returned to callercan’t be used in catch or finally blocksTask, Task<T> or a custom type
get a reference to the Task first
... or just await
![Page 25: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/25.jpg)
How to use: error handling?• async Task or Task<T>
Returned Task State == FaultedException re-thrown when task is awaited
• async void methods (event handlers)Exception is thrown on the current synchronization context and the app will crash...
![Page 26: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/26.jpg)
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”
• AggregateExceptionLoop through, handle or throw as required...
![Page 27: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/27.jpg)
• Cancellation is optionalusually exposed an Async() method overload that takes a CancellationToken parametercalling code uses the tokenCancellation.None means it won’t be cancelled by the caller (useful when the cancellation parameter isn’t optional)
How to use: cancellation?
![Page 28: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/28.jpg)
• Cancellation is optionalcancelled async tasks complete (but time for this to happen isn’t guaranteed)
How to use: cancellation?
![Page 29: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/29.jpg)
• Specifying a timeout is optionalfor HttpClient, set Timeout
some Async methods accept a timeout parameter
more generally, use CancellationToken (timeout)
How to use: timeouts?
![Page 30: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/30.jpg)
• Progress reporting is optionalprovide another Async overload with an IProgress<T> parameterbasic Progress<T> implementation can be usedexposes EventHandler<T> ProgressChanged
How to use: progress reporting?
send events to track progress
![Page 31: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/31.jpg)
BONUS: Combinators• Wait on multiple tasks
Task.WhenAll (IEnumerable<Task>)
- requires all the tasks to be completedTask.WhenAny(IEnumerable<Task>)
- returns when any of the tasks completes
this kind of loop fine for small numbersof Tasks
![Page 32: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/32.jpg)
WARNING: Await, and UI, and deadlocks
http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx
![Page 33: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/33.jpg)
MOAR MOBILEiOS & Android too!
![Page 34: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/34.jpg)
.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 appsonly have async APIs
![Page 35: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/35.jpg)
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
![Page 36: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/36.jpg)
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
![Page 37: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/37.jpg)
Xamarin APIs
• Xamarin.Mobile Geolocator.GetPositionAsync()Contact.SaveThumbnailAsync()
• Xamarin.Auth
FormAuthenticator.SignInAsync()Request.GetResponseAsync(cancellationToken)
• and many more...Xamarin cross-platform libraries
![Page 38: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/38.jpg)
Xamarin Component Store
• Many components already offer async APIs, eg. Parse!
Powerful, easy to use componentshttp://components.xamarin.com
![Page 39: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/39.jpg)
DEMODEMOParseTodo
![Page 40: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/40.jpg)
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
![Page 41: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/41.jpg)
Other tricks...
• Creating your own async Tasks
![Page 42: Async Await for Mobile Apps](https://reader033.fdocuments.us/reader033/viewer/2022042509/554f40cbb4c905cd048b5402/html5/thumbnails/42.jpg)
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